I have a json which has a List value and I want to use this value under a gridview.builder,
I tried that with a "for" it just taking first item of first list and repeat that according to lenght of related index, such as for first one (878, 878) second one (878, 878, 878) etc.
What am I missing?
My goal is getting related genre ids(I will turn them names later) beside related cards but now it looks like that;
My code and json sample are below;
body: Container(
padding: EdgeInsets.all(4),
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: mediaQueryData.orientation == Orientation.portrait ? 1 : 2,
childAspectRatio: mediaQueryData.orientation == Orientation.portrait ? MediaQuery.of(context).size.height/MediaQuery.of(context).size.width/1.05 : MediaQuery.of(context).size.width/(MediaQuery.of(context).size.height-29),
),
itemCount: snapshot.data.results.length,
itemBuilder: (context, index) {
return
Padding(
padding: const EdgeInsets.all(3.0),
child: Container(
child: Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[
InkWell(
onTap: (){
setState(() {
firstRun = true;
String tempName;
tempName = _name;
String name = "imdbid=${snapshot.data.results[index].id}&language=${AppLocalizations.of(
context)
.translate(
'lan_code')}#$tempName";
saveNamedPreference(name).then((
bool committed) {Navigator.of(context).pushNamed(
MovieDetailPage.routeName);
});
});
},
child: Container(
width: MediaQuery.of(context).size.width,
alignment: Alignment.bottomLeft,
height: 245,
child: Stack(
alignment: Alignment.centerLeft,
children: <Widget>[
Card(
margin: EdgeInsets.only(top: 40),
elevation: 5,
child: Stack(
children: <Widget>[
Container(
padding:EdgeInsets.only(right:10.0),
alignment: Alignment.bottomRight,
child: CircularPercentIndicator(
radius: 40.0,
lineWidth: 5.0,
percent: snapshot.data.results[index].voteAverage/10,
center: Stack(
children: <Widget>[
Text(
snapshot.data.results[index].voteAverage.toString(),
style: TextStyle(
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..color = Colors.black,
),
),
new Text(snapshot.data.results[index].voteAverage.toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.amber,),),
],
),
progressColor: Colors.amber,
),
),
Container(
padding: mediaQueryData.orientation == Orientation.portrait ? EdgeInsets.only(left:170.0, top: 10) : EdgeInsets.only(left:140.0, top: 10),
alignment: Alignment.topLeft,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("${snapshot.data.results[index].title}",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Theme.of(context).brightness == Brightness.dark ? Colors.white : Colors.black,shadows: [
Shadow(color:Colors.grey,blurRadius: 0,offset: Offset(0,2)),
]),maxLines: 3, textAlign: TextAlign.left,),
Text("(${snapshot.data.results[index].releaseDate.toString().substring(0,4)})",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Theme.of(context).brightness == Brightness.dark ? Colors.white : Colors.black,shadows: [
Shadow(color:Colors.grey,blurRadius: 0,offset: Offset(0,2)),
]),maxLines: 1, textAlign: TextAlign.left),
Container(
width: 150,
height: 120,
child: GridView.builder(
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: 2/1,),
itemCount: snapshot.data.results[index].genreIds.length,
itemBuilder: (context, index) {
for(var i = 0; i < snapshot.data.results[index].genreIds.length; i++, index++){
print("${snapshot.data.results[index].genreIds.toString()}");
return Text("${snapshot.data.results[index].genreIds.toString()}",);
}
return Container();}),
),
],
),
),
],
),
),
Card(
elevation: 3,
child: Padding(
padding: mediaQueryData.orientation == Orientation.portrait ? const EdgeInsets.all(6.0) : const EdgeInsets.all(4.0),
child: Container(
alignment: Alignment.centerLeft,
width: mediaQueryData.orientation == Orientation.portrait ? 140 : 120,
height: 245,
child: ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Image.network(
snapshot.data.results[index].posterPath != null ? "http://image.tmdb.org/t/p/w500/${snapshot
.data.results[index].posterPath}" : "https://i.hizliresim.com/bbn0VB.jpg", fit: BoxFit.contain,),
),
),
),
),
],
),
),
),
],
),
),
);
}
),
),
First, to avoid confusion, name your index variable differently in both builders, then you can easily see that you can use both indexes instead of the for loop :
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
itemCount: snapshot.data.results.length,
itemBuilder: (context, index) {
return GridView.builder(
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
itemCount: snapshot.data.results[index].genreIds.length,
itemBuilder: (context, indexGenre) {
return Text("${snapshot.data.results[index].genreIds[indexGenre].toString()}");
},
return Container();
);
}
)
If you still want to use your loops in a more "programmative" way, then use the GridView default constructor directly (not the GridView.builder constructor) so that you can build the list of children "manually" :
GridView(
children: <Widget>[
for (var film in snapshot.data.results)
GridView(
children: <Widget>[
for (var genre in film.genreIds)
Text("${genre.toString()}")
],
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
)
],
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
),
Note that this last solution requires Dart > 2.3.
Related
import 'package:flutter/material.dart';
import 'package:smart_uild/assets.dart';
class Myprofile extends StatelessWidget {
const Myprofile({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xff384A62),
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
),
title: const Text("My Profile"),
elevation: 0,
),
body: Padding(
padding: const EdgeInsets.only(
left: 18.0,
top: 18,
),
child: Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(
side: const BorderSide(color: Color(0xff384A62), width: 1),
borderRadius: BorderRadius.circular(10),
),
child: Container(
width: 350,
height: 151,
color: Colors.white,
child: Row(
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(10),
child: Expanded(
child: Image.asset(
image1,
width: 100,
height: 100,
),
flex: 2,
),
),
),
Expanded(
child: Container(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(top: 38.0),
child: Column(
children: [
const Expanded(
flex: 5,
child: ListTile(
title: Text(
"Genova",
style: TextStyle(
color: Color(0xff384A62),
fontSize: 20,
fontWeight: FontWeight.w400),
),
),
),
Expanded(
flex: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const SizedBox(
width: 8,
),
TextButton.icon(
style: TextButton.styleFrom(
textStyle:
const TextStyle(color: Colors.white),
backgroundColor: const Color(0xffFF0000),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6.0),
),
),
onPressed: () => {},
icon: const Icon(
Icons.power_off,
color: Colors.white,
),
label: const Text(
'DUTY SIGN OFF',
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w400),
),
),
const SizedBox(
width: 8,
),
],
),
),
const SizedBox(
width: 8,
),
],
),
),
),
),
],
),
),
elevation: 0,
margin: const EdgeInsets.all(10),
),
),
);
}
}
I want to display of image in listview which read data from firestore. I declare attribure image as array type.Here is my collection.
When i run the code, the image only display the first index of array and the second will read the first index of array like this. supposedly the second slide of image, it will display the second index of array from firestore.
Here is my code.
import 'package:carousel_pro/carousel_pro.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fyp/shared/Loading.dart';
import 'package:google_fonts/google_fonts.dart';
class ListTask extends StatefulWidget {
#override
_ListTaskState createState() => _ListTaskState();
}
final FirebaseAuth auth = FirebaseAuth.instance;
Stream<QuerySnapshot> getUserRd(BuildContext context) async* {
final FirebaseUser rd = await auth.currentUser();
yield* Firestore.instance.collection("Task").where('uid',isEqualTo: rd.uid).snapshots();
}
class _ListTaskState extends State<ListTask> {
List<NetworkImage> _listOfImages = <NetworkImage>[];
#override
Widget build(BuildContext context) {
return Container(
child: StreamBuilder(
stream: getUserRd(context),
builder: (context, snapshot){
if (snapshot.hasError || !snapshot.hasData) {
return Loading();
} else{
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index){
DocumentSnapshot ba = snapshot.data.documents[index];
_listOfImages =[];
for(int i =0; i < snapshot.data.documents[index].data['url'].length; i++){
_listOfImages.add(NetworkImage(snapshot.data.documents[index].data['url'][i]));
}
return Card(
child:ListTile(
title: Container(
alignment: Alignment.centerLeft,
child: Column(
children: <Widget>[
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Sumber Aduan: ", style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
Text(ba['sumberAduan'], style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
],
),
),
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Nombor Aduan: ", style: GoogleFonts.lato(fontWeight: FontWeight.bold)),
Text(ba['noAduan'], style: GoogleFonts.lato(fontWeight: FontWeight.bold)),
],
),
),
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Status: ", style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
Text(ba['verified'], style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
],
),
),
Column(
children: [
Container(
margin: EdgeInsets.all(10.0),
height: 200,
decoration: BoxDecoration(
color: Colors.white
),
width: MediaQuery.of(context).size.width,
child: Carousel(
boxFit: BoxFit.cover,
images: _listOfImages,
autoplay: false,
indicatorBgPadding: 5.0,
dotPosition: DotPosition.bottomCenter,
animationCurve: Curves.fastLinearToSlowEaseIn,
animationDuration: Duration(milliseconds: 2000),
),
)
],
)
],
),
),
onTap: () {listAddress(ba['id']);}
)
);
});
}
}),
);
}
void listAddress(String id) {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(10.0),
topRight: const Radius.circular(10.0)
)
),
context: context,
builder: (builder){
return StreamBuilder(
stream:Firestore.instance.collection("Task").document(id).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Loading();
} else {
return Container(
height: 150,
child: Container(
padding: EdgeInsets.fromLTRB(20.0, 3, 30.0, 5.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
alignment: Alignment.topLeft,
width: 220,
margin: EdgeInsets.only(top:26, left: 14),
child: Row(
children: [
Text("Kawasan: ", textAlign: TextAlign.left,style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
Text( snapshot.data['kawasan'], textAlign: TextAlign.left,style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
],
),
),
Container(
width: 220,
margin: EdgeInsets.only(top:4, left: 15),
child: Row(
children: [
Text("Nama Jalan :", textAlign: TextAlign.left,style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
Text(snapshot.data['naJalan'], textAlign: TextAlign.left,style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
],
),
),
Container(
width: 220,
margin: EdgeInsets.only(top:4, left: 15),
child: Row(
children: [
Text("Kategori : ", textAlign: TextAlign.left,style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
Text(snapshot.data['kategori'], textAlign: TextAlign.left,style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
],
),
),
],
),
)
],
),
],
),
),
);
}
}
);
}
);
}
}
can someone explain to me about this problem? is there anything that I missed out? someone help me please?
The code is correct. You have exactly the same links in your list url, that's why you're getting the same picture.
I am making meme generator app . And i need to show multiple texts over the images , I am able to get one draggable text but i want the user to add multiple text . can you please help me out .
I am fetching the image via my api and i have created a stacked layout on which i have added my text .
I have provided some text customization option to users . I want users to add multiple text and they can also customize them
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'dart:convert';
import 'package:admob_flutter/admob_flutter.dart';
import 'package:bordered_text/bordered_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:meme_app/Screens/CustomMemes.dart';
import 'package:meme_app/Services/admob_services.dart';
import 'dart:ui' as ui;
import 'package:meme_app/image editor/lists.dart';
import 'package:path_provider/path_provider.dart';
class CustomSceen3 extends StatefulWidget {
final String imgUrl;
final File imgFile;
CustomSceen3({
this.imgUrl,
this.imgFile,
});
#override
_CustomSceen3State createState() => _CustomSceen3State();
}
class _CustomSceen3State extends State<CustomSceen3> {
GlobalKey<ScaffoldState> scaffoldState = GlobalKey();
Size size = Size(600, 800);
List<Widget> data = <Widget>[];
Offset offset = Offset.zero;
String addedText = '';
String newText;
int total=0;
//settings
Color pickerColor = Color(0xffffffff);
Color currentColor = Color(0xffffffff);
double textSize = 28.0;
String customFont = 'Aileron-Black';
GlobalKey _key = GlobalKey();
File _imageFile;
Random rng = new Random();
int whiteSpace = 0;
bool strike = false;
double strokeSize = 2.0;
Color strokePickerColor = Color(0xff000000);
Color strokeCurrentColor = Color(0xff000000);
TextEditingController myController = TextEditingController()
..text = "";
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Expanded(
child: Container(
color: Colors.black,
child: Center(
child: SingleChildScrollView(
child: Container(
color: Colors.white,
child: RepaintBoundary(
key: _key,
child: Stack(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: whiteSpace.toDouble() * 5,
color: Colors.white,
),
widget.imgFile == null
? Image(
image: NetworkImage(widget.imgUrl),
)
: Image.file(widget.imgFile, height: 300,
width: MediaQuery
.of(context)
.size
.width,
fit: BoxFit.fill,),
],
),
Positioned(
left: offset.dx,
top: offset.dy,
child: GestureDetector(
onPanUpdate: (details) {
setState(() {
offset = Offset(
offset.dx + details.delta.dx, offset.dy + details.delta.dy);
});
},
child: Container(
child: BorderedText(
strokeColor: strokeCurrentColor,
strokeWidth: strokeSize ,
child: Text(
addedText,
style: TextStyle(
fontFamily: customFont,
fontSize: textSize,
color: currentColor
),
),
),
),
),
),
],
),
),
),
),
),
)
),
Container(
color: Colors.black,
height: 80.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.all(5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DropdownButton<int>(
style: TextStyle(
color: Colors.white,
),
value: whiteSpace,
dropdownColor: Colors.black87,
isDense: true,
icon: Icon(Icons.padding, color: Colors.white,),
iconSize: 30,
onChanged: (int newValue) {
setState(() {
whiteSpace = newValue;
});
},
items: whiteSpaceList
.map<DropdownMenuItem<int>>((int value) {
return DropdownMenuItem<int>(
value: value,
child: Text(value.toString() + "%"),
);
}).toList(),
),
Center(
child: Text(
"Add Space", maxLines: 2, overflow: TextOverflow
.clip,
style: TextStyle(
fontSize: 11, color: Colors.white),
),
)
],
),
),
Padding(
padding: EdgeInsets.all(5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
icon: Icon(Icons.text_format, color: Colors.white,
size: 30,),
onPressed: () {
TextDialog();
}
),
Text(
"Text", maxLines: 2, overflow: TextOverflow.clip,
style: TextStyle(fontSize: 11, color: Colors.white),
)
],
),
),
Padding(
padding: EdgeInsets.all(5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
icon: Icon(
Icons.emoji_emotions_outlined, color: Colors
.white, size: 30,),
onPressed: null
),
Text(
"Sticker", maxLines: 2, overflow: TextOverflow.clip,
style: TextStyle(fontSize: 11, color: Colors.white),
)
],
),
),
Padding(
padding: EdgeInsets.all(5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
icon: Icon(Icons.download_outlined, color: Colors
.white, size: 30,),
onPressed: null
),
Text(
"Save", maxLines: 2, overflow: TextOverflow.clip,
style: TextStyle(fontSize: 11, color: Colors.white),
)
],
),
),
Padding(
padding: EdgeInsets.all(5.0),
child: GestureDetector(
onTap: (){
setTextStyle();
},
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Aa",style:TextStyle(
fontSize: 30,color: Colors.white,fontFamily: 'ComicRelief'
),
),
Text(
"Font", maxLines: 2, overflow: TextOverflow.clip,
style: TextStyle(fontSize: 11, color: Colors.white),
)
],
),
),
),
],
)
)
],
),
),
);
}
Widget setTextStyle(){
showDialog(
context: context,
builder: (BuildContext context){
return Dialog(
backgroundColor: Colors.black54,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: SizedBox(
height: 400,
child: Center(
child: Column(
children: [
CustomTextStyle(
tittle: "Black Text",
color: Colors.white,
strokecolor: Colors.white,
font: 'OpenSans-Regular',
strokewidth: 0.0,
onTap: (){
setState(() {
strokeSize= 0.0;
currentColor=Colors.black;
customFont= 'OpenSans-Regular';
strokeCurrentColor=Colors.white;
Navigator.of(context).pop();
});
},
),
CustomTextStyle(
tittle: "STANDARD MEME",
color: Colors.white,
strokecolor: Colors.black,
font: 'Anton',
strokewidth: 3.0,
onTap: (){
setState(() {
strokeSize= 3.0;
currentColor=Colors.white;
customFont= 'Anton';
strokeCurrentColor=Colors.black;
addedText=addedText.toUpperCase();
Navigator.of(context).pop();
});
},
),
CustomTextStyle(
tittle: "Modern Meme",
color: Colors.black,
strokecolor: Colors.white,
font: 'OpenSans-Regular',
strokewidth: 3.0,
onTap: (){
setState(() {
strokeSize= 3.0;
currentColor=Colors.black;
customFont= 'OpenSans-Regular';
strokeCurrentColor=Colors.white;
Navigator.of(context).pop();
});
},
),
CustomTextStyle(
tittle: "Dark Modern Meme",
color: Colors.white,
strokecolor: Colors.black,
font: 'OpenSans-Regular',
strokewidth: 3.0,
onTap: (){
setState(() {
strokeSize= 3.0;
currentColor=Colors.white;
customFont= 'OpenSans-Regular';
strokeCurrentColor=Colors.black;
Navigator.of(context).pop();
});
},
),
CustomTextStyle(
tittle: "Black Object White Outline",
color: Colors.black,
strokecolor: Colors.white,
font: 'Aileron-Bold',
strokewidth: 3.0,
onTap: (){
setState(() {
strokeSize= 3.0;
currentColor=Colors.black;
customFont= 'Aileron-Bold';
strokeCurrentColor=Colors.white;
Navigator.of(context).pop();
});
},
),
CustomTextStyle(
tittle: "White Object Black Outline",
color: Colors.white,
strokecolor: Colors.black,
font: 'Aileron-Bold',
strokewidth: 3.0,
onTap: (){
setState(() {
strokeSize= 3.0;
currentColor=Colors.white;
customFont= 'OpenSans-Regular';
strokeCurrentColor=Colors.black;
Navigator.of(context).pop();
});
},
),
CustomTextStyle(
tittle: "Yellow Subtittle",
color: Color(0xfeFFE400),
strokecolor: Colors.black,
font: 'OpenSans-Regular',
strokewidth: 3.0,
onTap: (){
setState(() {
strokeSize= 3.0;
currentColor=Color(0xfeFFE400);
customFont= 'OpenSans-Regular';
strokeCurrentColor=Colors.black;
Navigator.of(context).pop();
});
},
)
],
),
),
),
),
);
}
);
}
Widget TextDialog() {
showDialog(
context: context,
barrierDismissible: true, // user must tap button!
builder: (BuildContext context) {
return ListView(
children:[ Container(color: Colors.black54,
child: Dialog(
backgroundColor: Colors.transparent,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
children: [
IconButton(
icon: Icon(Icons.invert_colors, color: Colors.white),
onPressed: null),
IconButton(
icon: Icon(Icons.add_circle, color: Colors.white),
onPressed: null),
IconButton(
icon: Icon(Icons.remove_circle, color: Colors.white),
onPressed: null),
IconButton(icon: Icon(Icons.format_align_center_outlined), onPressed: null)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
OutlineButton(
borderSide: BorderSide(width: 1.0,
color: Colors.white,
style: BorderStyle.solid),
onPressed: () {
setState(() {
addedText = myController.text;
Navigator.of(context).pop();
}
);
},
child: Text(
"Got it", style: TextStyle(color: Colors.white),
),
)
],
)
],
),
textfield(),
Container(height: 50,
color: Colors.black,
child: ListView.builder(
itemCount: colors.length,
scrollDirection: Axis.horizontal, physics: ScrollPhysics(),
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: GestureDetector(
onTap: () {
setState(() {
currentColor = colors[index];
Navigator.of(context).pop();
TextDialog();
});
},
child: Container(
width: 40.0,
decoration: BoxDecoration(
color: colors[index], //this is the important line
shape: BoxShape.circle,
border: Border.all(
width: 2.0, color: Colors.white60)
),
),
),
);
},
),
),
],
),
),
),
),
],
);
}
);
}
Widget textfield() {
return TextField(
controller: myController,
maxLines: 10,
);
}
}
class CustomTextStyle extends StatelessWidget {
CustomTextStyle({this.color,this.tittle,this.strokecolor,this.font,this.strokewidth,this.onTap
});
final Color color;
final Color strokecolor;
final double strokewidth;
final String tittle;
final String font;
final Function onTap;
#override
Widget build(BuildContext context) {
return ListTile(
onTap: onTap,
title: BorderedText(
strokeColor: strokecolor,
strokeWidth: strokewidth,
child: Text(
tittle,
style: TextStyle(
color: color,fontFamily: font,fontSize: 17,letterSpacing: 1.05
),
),
),
);
}
}
I have often found really quick and very competent help here. And hope you can help me again.
I have had an error message for three days, which I cannot get solved.
I explained the problem to you in a small video.
The link to the video is: "https://drive.google.com/file/d/1T9uOnEaNp5W6_kcO6eV9o64Fp3sRkB3f/view?usp=sharing"
I really hope you see the mistake I don't see!
This is the code of the Foodcard, which according to Flutter should cause the error:
The method '-' was called on null.
Receiver: null
Tried calling: -(30.0)
The relevant error-causing widget was:
FoodCard file:///C:/Users/stefa/AndroidStudioProjects/cronum_app_web%20-%20Kopie/lib/Components/ProviderComponents.dart:298:9
FoodCard:
class FoodCard extends StatelessWidget {
FoodCard({
#required this.description,
#required this.imagePath,
#required this.price,
#required this.foodName,
#required this.foodItem,
#required this.increaseCallback,
#required this.decreaseCallback,
this.count = 0,
});
final double radius = 40;
static double listViewHeight;
final double margin = 15;
final double containerHeight = 130;
final int count;
final String imagePath;
final String foodName;
final String price;
final String description;
final FoodItem foodItem;
final Function increaseCallback;
final Function decreaseCallback;
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 10, vertical: margin),
width: 220,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(radius),
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.topRight,
colors: ([
gradientColor1.withOpacity(opacityOfHeader),
primaryColor.withOpacity(opacityOfHeader),
gradientColor2.withOpacity(opacityOfHeader),
]),
),
boxShadow: [
BoxShadow(
blurRadius: 8,
color: Colors.black.withOpacity(0.3),
offset: Offset(5, 5),
),
],
color: Colors.white,
),
child: Column(
children: <Widget>[
Stack(
alignment: Alignment.center,
children: <Widget>[
Column(
children: <Widget>[
SizedBox(
height: listViewHeight - margin * 2 - containerHeight,
),
Container(
height: containerHeight,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(radius),
topRight: Radius.circular(radius),
bottomLeft: Radius.circular(radius),
bottomRight: Radius.circular(radius),
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
offset: Offset(0, -5),
blurRadius: 8)
],
color: Colors.white),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 40),
child: Center(
child: Text(
foodName,
style: TextStyle(
color: Colors.black,
fontSize: 17,
fontWeight: FontWeight.w900,
),
),
),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 20, vertical: 15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(
foodItem: foodItem,
increaseCount: increaseCallback,
decreaseCount: decreaseCallback,
),
),
);
},
child: Container(
height: 30,
width: 80,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
offset: Offset(5, 5),
color: Colors.black.withOpacity(0.3),
blurRadius: 8)
],
color: buttonColor,
borderRadius: BorderRadius.circular(25),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 7, vertical: 5),
child: Center(
child: Text(
'Details',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
Container(
color: Colors.grey.withOpacity(0.5),
height: 25,
width: 1,
),
Container(
height: 30,
width: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: buttonColor,
boxShadow: [
BoxShadow(
blurRadius: 8,
color: Colors.black.withOpacity(0.3),
offset: Offset(5, 5),
),
],
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
children: <Widget>[
InkWell(
onTap: decreaseCallback,
child: Container(
height: 22,
width: 22,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(5),
color: buttonColor,
),
child: Center(
child: Icon(
Icons.remove,
color: Colors.white,
size: 22,
),
),
),
),
Text(
count.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w900,
),
),
InkWell(
onTap: increaseCallback,
child: Container(
height: 22,
width: 22,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(15),
color: Colors.white,
),
child: Center(
child: Icon(
Icons.add,
color: buttonColor,
size: 22,
),
),
),
),
],
),
),
],
),
),
],
),
),
],
),
Positioned(
top: 30,
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(
foodItem: foodItem,
increaseCount: increaseCallback,
decreaseCount: decreaseCallback,
),
),
);
},
child: Image(
height: listViewHeight / 2,
width: listViewHeight / 2,
image: AssetImage(imagePath),
),
),
),
],
)
],
),
);
}
If it is not because of the FoodCard, the function with which I create the list of Foodcards could also be the problem.
I am amazed by the error message because it is so extremely non-specific. Before I automated the creation of the list, everything worked wonderfully.
List<Widget> buildEntdeckenCards() {
List<Widget> foodCardList = [];
for (FoodItem foodItem in top10) {
print(foodItem.foodName);
foodCardList.add(
FoodCard(
description: foodItem.description,
foodName: foodItem.foodName,
foodItem: foodItem,
price: foodItem.price,
imagePath: foodItem.imagePath,
decreaseCallback: () {
decreaseCount(foodItem);
},
increaseCallback: () {
increaseCount(foodItem);
},
),
);
}
return foodCardList;
}
I think your listViewHeight variable is null, and you are trying to use it in expression
SizedBox(height: listViewHeight - margin * 2 - containerHeight,),
I think that's why you see the following error The method '-' was called on null. Assign some value to listViewHeight before using it.
I have a for Loop where articles get loaded into a Widget and I only want one to be enabled, so how can I do that?
So far I got it working, but it doesn't recognise if I pressed another Button and I am relatively new to Flutter so I don't exactly know how I can implement such a feature.
Widget for Articles
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:wiegon/icons/nuleo_icons.dart';
import 'package:wiegon/main.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:wiegon/pages/control_screen.dart';
import 'package:wiegon/widgets/widgets.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:page_transition/page_transition.dart';
class ArticleandAmount extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
leading: Builder(
builder: (BuildContext context) {
return IconButton(
icon: new SvgPicture.asset(wiegonLogo,
allowDrawingOutsideViewBox: true,
semanticsLabel: 'Wiegon Logo'),
onPressed: null,
);
},
),
title: Text(
"Artikel und Menge",
style: TextStyle(fontSize: 18, color: Color(0xffFDFEFE)),
),
backgroundColor: Color(0xff466988),
),
body: Articleamount(),
endDrawer: Enddrawer());
}
}
class Articleamount extends StatefulWidget {
#override
_ArticleamountState createState() {
return _ArticleamountState();
}
}
String displayedWeight;
String displayedTotalPrice;
String displayedPrice;
String articleID;
String unit = "";
String articleSelected = "Artikel wählen";
class _ArticleamountState extends State<Articleamount> {
final amountController = TextEditingController();
static Color disabledColor = mainColor.withOpacity(0.5);
double price = 0.0;
double inputAmount = 0;
bool isArticleSelected = false;
bool isPriceSelected = false;
Color buttonColor = disabledColor;
String totalPrice = "0";
#override
void dispose() {
// Clean up the paremeters when the widget is disposed.
unit = "";
articlesList = {};
articleSelected = "Artikel wählen";
amountController.dispose();
super.dispose();
}
Widget articleCard(
String articleName, IconData icon, double priceForArticle) {
String tempunit = articleName.split("|")[1];
String tempID = articleName.split("&")[1].split("|")[0];
articleName = articleName.split("&")[0];
return SingleChildScrollView(
child: Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
width: 300,
height: 120,
padding: EdgeInsets.all(5),
child: MaterialButton(
child: Align(
alignment: Alignment.centerLeft,
child: Text(
articleName,
overflow: TextOverflow.fade,
style: TextStyle(fontWeight: FontWeight.bold),
)),
highlightColor: Colors.blue,
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
10,
)),
elevation: 2,
onPressed: () {
articleSelected = articleName;
articleID = tempID;
setState(() {
amountController.text = "";
totalPrice = "0";
buttonColor = disabledColor;
inputAmount = 0;
unit = tempunit;
price = priceForArticle;
isArticleSelected = true;
});
},
),
));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(children: <Widget>[
FractionallySizedBox(
widthFactor: deviceWidth(context),
child: Center(
child: Container(
width: 600,
margin: EdgeInsets.only(top: 35),
color: Colors.transparent,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
progressBar(Nucleo.checked, "Bürger", true),
progressLine(true, context),
progressBar(
Nucleo.selected_two, "Artikel und Menge", true),
progressLine(false, context),
progressBar(Nucleo.three, "Buchung", false),
],
),
Container(
margin: EdgeInsets.only(top: 35),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Bürger".toUpperCase(),
style: TextStyle(
fontSize: 13,
color: Colors.grey,
fontWeight: FontWeight.bold),
),
new Padding(
padding: EdgeInsets.only(top: 3),
),
Text(
getCitizenInformation(),
style: TextStyle(
fontSize: 17, color: secondaryColor),
)
],
),
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.only(top: 30),
// width: 600,
child: Row(children: [
Column(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Artikel und Menge wählen",
style: TextStyle(
color: secondaryColor,
fontSize: 21,
fontWeight: FontWeight.bold),
),
Container(
margin: EdgeInsets.only(top: 4),
height: 5,
width: 30,
color: secondaryColor)
],
),
]),
)
],
),
Row(
children: [
Container(
margin: EdgeInsets.only(top: 40),
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.transparent),
width: 600,
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Wrap(
alignment: WrapAlignment.spaceBetween,
children: <Widget>[
for (var article in articlesList.keys)
articleCard(
article,
MdiIcons.chessQueen,
articlesList[article])
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 40),
height: 70,
width: 600,
decoration: new BoxDecoration(
borderRadius:
BorderRadius.circular(10),
color: Colors.white),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 220,
margin:
EdgeInsets.only(left: 10),
child: TextField(
onChanged: (text) {
totalPrice = calculatePrice(
text, price);
},
keyboardType:
TextInputType.number,
controller: amountController,
decoration: InputDecoration(
labelStyle: TextStyle(
fontSize: 13),
labelText:
"$articleSelected"),
),
),
Text(
"á € $price / $unit",
style: TextStyle(
color: primaryColor,
fontSize: 20),
),
Text(
"$totalPrice€",
style: TextStyle(
color: secondaryColor,
fontSize: 20,
fontWeight:
FontWeight.bold),
),
],
),
),
],
),
Container(
margin: EdgeInsets.only(top: 30),
child: Row(
crossAxisAlignment:
CrossAxisAlignment.end,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
ButtonTheme(
minWidth: 280,
height: 50,
child: OutlineButton(
borderSide: BorderSide(
color: mainColor, width: 2),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(
10)),
child: Text(
"Zurück",
style: TextStyle(
color: mainColor,
fontSize: 16,
),
),
onPressed: () {
Navigator.pop(context);
},
),
),
MaterialButton(
minWidth: 280,
height: 50,
color: buttonColor,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(
10)),
child: Text(
"Weiter",
style: TextStyle(
color: Colors.white,
fontSize: 16,
),
),
onPressed: () {
if (isArticleSelected == true &&
isPriceSelected == true &&
inputAmount != 0) {
Navigator.push(
context,
PageTransition(
type: PageTransitionType
.rightToLeftWithFade,
child:
Controlscreen()));
} else {
Fluttertoast.showToast(
msg:
"Eingaben bitte überprüfen",
toastLength:
Toast.LENGTH_SHORT,
gravity:
ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor:
Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
}),
],
),
)
]),
),
],
),
]))))
]));
}
String calculatePrice(String inputText, double price) {
double amount;
if (inputText.isNotEmpty) {
amount = double.parse(inputText);
} else {
amount = 0;
}
double total = (amount * price);
setState(() {
totalPrice = total.toStringAsFixed(2);
isPriceSelected = true;
inputAmount = amount;
buttonColor = mainColor;
});
displayedTotalPrice = totalPrice;
displayedWeight = amount.toString();
displayedPrice = price.toString();
return totalPrice;
}
}
You can use a variable to know if a button is already pressed. Like this:
var isSelected = false;
FlatButton(
onPressed: () => { isSelected = true },
child: Text(
"Selling"
),
color: isSelected ? Theme.of(context).primaryColor : Colors.grey,
),