Flutter Getx on list view error the improper use of a GetX has been detected - flutter

I am trying to use Getx on simple ListView but its showing error that [Get] the improper use of a GetX has been detected.
Widget getBody() {
var size = MediaQuery.of(context).size;
final controller = Get.put(PassionController());
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(left: 30, right: 30),
child: Column(
children: [
GetX<PassionController>(
builder: (_) => ListView.builder(
itemCount: controller.passionItems.length,
itemBuilder: (context, index) {
return ListTile(
title:
Text('Number: ${controller.passionItems[index]}'),
);
})),
GestureDetector(
onTap: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => MyHomePage()));
},
child: Container(
width: size.width,
height: 55,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30), color: Colors.white
// gradient:
// LinearGradient(colors: [primary_one, primary_two])
),
child: Center(
child: Text(
"Continue",
style: TextStyle(
color: kPrimarycolor,
fontSize: 18,
fontWeight: FontWeight.w500),
),
),
),
)
],
),
),
);
}
I also try GetxBuilder but same error showing. I already wrap GetMaterial on main.dart

Related

Why does Late Initialization Error occur?

The application has the function of adding news to favorites. But when I go to the Favorites page, I get the error "Late Initialization Error: Field "article" has not been initialized.
The problem is in the button "Details", in the line:
MaterialPageRoute(builder: (context) => ArticlePage(article: article,))
Please help me solve the problem. Below is the code for this page:
class FavScreen extends StatefulWidget {
const FavScreen({Key? key}) : super(key: key);
#override
State<FavScreen> createState() => _FavScreenState();
}
class _FavScreenState extends State<FavScreen> {
late final Article article;
final _fireStore = FirebaseFirestore.instance.collection('favoriteItems');
#override
void initState() {
article = Article(
author: article.author,
title: article.title,
description: article.description,
url: article.url,
urlToImage: article.urlToImage,
publishedAt: article.publishedAt,
content: article.content,
source: article.source,
);
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Favorite News', style: TextStyle(color: Colors.white)),
backgroundColor: Color(0xfff27935),
),
body:
StreamBuilder(
stream: _fireStore.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if(!snapshot.hasData) {
return Text('No featured news');
} else {
return ListView.builder(
itemCount: snapshot.data?.docs.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: Container(
margin: EdgeInsets.all(12.0),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12.0),
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 3.0,
),
]),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 200.0,
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(snapshot.data?.docs[index].get('image')), fit: BoxFit.cover),
borderRadius: BorderRadius.circular(12.0),
),
),
SizedBox(
height: 8.0,
),
Container(
child: Row(
textDirection: TextDirection.ltr,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: EdgeInsets.all(6.0),
decoration: BoxDecoration(
color: Color(0xfff27935),
borderRadius: BorderRadius.circular(30.0),
),
child: Text(
snapshot.data?.docs[index].get('name'),
style: TextStyle(
color: Colors.white,
),
),
),
IconButton(
onPressed: () {
_fireStore.doc(snapshot.data?.docs[index].id).delete();
},
icon: const Icon(Icons.bookmark_remove)),
]
)
),
SizedBox(
height: 8.0,
),
Text(
snapshot.data?.docs[index].get('title'),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
),
),
SizedBox(
height: 10.0,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ArticlePage(
article: article,
)));
},
child: new Text("DETAILS", style: TextStyle(
fontSize: 12.0,
),
),
)
],
),
),
);
}
);
}
},
)
);
}
}
article = Article(
author: article.author,
title: article.title,
description: article.description,
url: article.url,
urlToImage: article.urlToImage,
publishedAt: article.publishedAt,
content: article.content,
source: article.source,
);
You're trying to initialize article by creating a new Article with values from article. article is uninitialized however, so it fails to read these values and spits out an error.
I'm not quite sure what you want to achieve, but I guess you want to pass in an Article into the widget and initialize the article variable in your state class with that?

Not showing the future builder of hot products which is placed after the department future builder in column

I am trying to show two future builders with gridview in the column widget, but it is showing me one future builder of the department and not showing the other future builder when scrolling it. how to show the future builder of hot product? it will be helpful for me
import 'dart:convert';
import 'package:apipractice/Models/Category_model.dart';
import 'package:apipractice/Models/Department_model.dart';
import 'package:apipractice/Models/HotProduct_model.dart';
import 'package:apipractice/Screens/Department.dart';
import 'package:apipractice/Screens/cart.dart';
import 'package:apipractice/Screens/categorry.dart';
import 'package:apipractice/Screens/products.dart';
import 'package:apipractice/Screens/selected_Category.dart';
import 'package:apipractice/Screens/subCategory.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future<HotProductModel> getHotProducts() async {
var data = jsonDecode(response.body);
if (response.statusCode == 200) {
return HotProductModel.fromJson(data[0]);
} else {
throw Exception('Failed to load album');
}
}
List images = [
"assets/Image1.jpeg",
"assets/Image2.jpeg",
"assets/Image3.jpeg",
"assets/Image4.jpeg",
"assets/Image5.jpeg",
"assets/Image6.jpeg",
];
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
child: ListTile(
leading: CircleAvatar(
child: Image(image: AssetImage("images/user.png")),
radius: 25,
),
title: Text(
"Username",
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text("abcuser#gmail.com"),
),
),
ListTile(
leading: Icon(Icons.note),
title: const Text('Show Product'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Products()),
);
},
),
ListTile(
leading: Icon(Icons.note),
title: const Text('Show Category'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Categorry()),
);
},
),
ListTile(
leading: Icon(Icons.note),
title: const Text('Department'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Department()),
);
},
),
],
),
),
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 24, 119, 197),
title: Text("Dubai Super Store"),
actions: [
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => Cart()),
),
);
},
icon: Icon(Icons.shopping_cart))
],
),
body: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: EdgeInsets.all(10),
height: 35,
width: double.infinity,
child: TextField(
decoration: InputDecoration(
hoverColor: Colors.blue,
prefixIconColor: Colors.blue,
labelText: "Search Product",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
),
Text(
"Note: Free Delivery Above Rs.2000",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red.shade700,
fontSize: 17),
),
Container(
height: 200,
width: double.infinity,
child: CarouselSlider.builder(
itemCount: images.length,
options: CarouselOptions(
height: 400,
viewportFraction: 1,
autoPlay: true,
),
itemBuilder: (context, index, realindex) {
final urlImages = images[index];
return buildImage(urlImages, index);
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
child: Column(
children: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Categorry()),
);
},
child: Image(
height: 70,
width: 70,
image: AssetImage("assets/Categories.jpeg"),
),
),
Text("Categories")
],
),
),
Container(
child: Column(
children: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SubCategory()),
);
},
child: Image(
height: 70,
width: 70,
image: AssetImage("assets/SubCategory.jpeg")),
),
Text("Sub Category")
],
),
)
],
),
SizedBox(height: 20),
Text(
"Department",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
color: Color.fromARGB(255, 16, 113, 192)),
),
FutureBuilder<DepartmentModel>(
future: getDepartment(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemCount: snapshot.data!.sKUDepartmentDetail!.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
var fetchid =
"${snapshot.data!.sKUDepartmentDetail![index].sKUDeptId}";
fetchCategory = fetchid;
setState(() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SelectedCategory()),
);
});
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
),
elevation: 10.0,
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
child: Stack(children: [
CachedNetworkImage(
imageUrl: snapshot
.data!
.sKUDepartmentDetail![index]
.imageUrl1!,
height: 150,
width: 200,
fit: BoxFit.fitWidth,
errorWidget: (context, url, error) {
return Image(
image: AssetImage(
"assets/placeholder.jpg"));
},
),
]),
),
Text(
snapshot
.data!.sKUDepartmentDetail![index].name!,
style: TextStyle(fontWeight: FontWeight.bold),
)
],
),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
// SizedBox(height: 20),
Text(
"Hot Product",
style: TextStyle(fontSize: 20),
),
FutureBuilder<HotProductModel>(
future: getHotProducts(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data!.productDetail!.length,
itemBuilder: (context, index) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(10),
),
boxShadow: [
BoxShadow(
color: Colors.black,
blurRadius: 3,
offset: Offset(1.0, 1.0),
)
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CachedNetworkImage(
imageUrl: snapshot.data!.productDetail![index]
.sKUImageURL1!,
height:
MediaQuery.of(context).size.height * 0.12,
width: double.infinity,
fit: BoxFit.fitWidth,
errorWidget: (context, url, error) {
return Image(
image: AssetImage(
"assets/placeholder.jpg"));
},
),
SizedBox(
height: 10,
),
Text(
"${snapshot.data!.productDetail![index].sKUName!}"),
Text(
"Rs: ${snapshot.data!.productDetail![index].salePrice!}",
style: TextStyle(
color: Colors.blue,
fontSize: 20,
fontWeight: FontWeight.bold),
),
Text(
"Rs: ${snapshot.data!.productDetail![index].retailPrice!}",
style: TextStyle(
decoration: TextDecoration.lineThrough,
color: Colors.red),
),
ElevatedButton(
onPressed: () {
var product = snapshot
.data!.productDetail![index].sKUId;
if (cartList.contains(product)) {
print("already exist");
} else {
cartList.add({
"Id": snapshot
.data!.productDetail![index].sKUId
});
}
},
child: Text("Add to Cart"))
],
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return CircularProgressIndicator();
}
})
],
),
),
);
}
This is the output of the code
[![output image][1]][1]
The problem is solved it is only not showing because of screen navigation bar now its fine

Flutter: How can i put Textfield input into a list to build a ListView.builder

Im trying to build a listviewbuilder since a few days. For that i need the textfield input from another screen. I looked a lot of tutorials and question but it doesnt work.Im trying to put the input from multiple textfields into multiple lists to build a Listview builder. It would be the best if i can save all Textfield input when i press on flatbutton. I hope someone can help me.
First page
List<String> time = ["8:00"];List<String>
List<String> where = ["Am See"];
List<String> who = ["Eric"];
List<String> when = ["Donnerstag 21.4.21"];
body: SingleChildScrollView(
physics: ScrollPhysics(),
child: Column(children: [
Upperscreen(size: size),
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: where.length,
itemBuilder: (BuildContext context, int Index) {
return Column(children: [
SizedBox(
height: 40,
),
Container(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Meet1()));
},
child: Container(
width: size.width * 0.9,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(70)),
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomRight,
colors: [
Colors.green,
Colors.orange,
],
),
),
child: Column(children: <Widget>[
SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.all(20),
child: Column(
children: <Widget>[
Text(
time[Index],
style: TextStyle(
color: Colors.white,
fontSize: 40,
fontWeight:
FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
who[Index],
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight:
FontWeight.bold),
),
Text(
when[Index],
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight:
FontWeight.bold),
),
Text(
where[Index],
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight:
FontWeight.bold),
Second page
child: Column(children: <Widget>[
SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.all(20),
child: Column(
children: <Widget>[
TextField(decoration: InputDecoration(hintText: " Time ")),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(hintText: " Who "),
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(hintText: " Date "),
),
SizedBox(
height: 10,
),
TextField(
decoration: InputDecoration(hintText: " Where "),
),
SizedBox(height: 10)
],
),
),
]));
Here the Flatbutton to add all.
return FlatButton(
child: Icon(
Icons.check_circle_outline_rounded,
color: Colors.green,
size: 120,
),
onPressed: () {
Navigator.of(context).popUntil((route) => route.isFirst);
},
Use a TextEditingController(), just like this -
TextEditingController() myController = TextEditingController();
Then assign this controller to controller property in TextField() -
TextField(
controller: myController,
),
Then use myController.text to retrieve the text from TextField(), and pass it to other pages as a String parameter -
Example -
class Screen1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
//....
body: FlatButton(
child: Icon(
Icons.check_circle_outline_rounded,
color: Colors.green,
size: 120,
),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (builder) {
return Screen2(text: myController.text);
}));
},
//....
),
);
}
}
Second Page -
class Screen2 extends StatelessWidget {
String text;
Screen2({this.text});
#override
Widget build(BuildContext context) {
return Scaffold(
//....
body: Text(text),
);
}
}
Go to this link to see another example
Now, here I used only 1 parameter "text". You can use multiple parameters like - "text1", "text2", "text3" and so on, as per your requirement, and use as many TextEditingController() for this.
*****Also Note that use of FlatButton() is depreciated, you can use a TextButton() instead

inavlid argument(s) /Exception caught by widgets library

I have an empty card widget which I used it for opening adding page, my problem is when I pushed from main categories screen I can add main category, but When I used this empty card button on sub category screen of any main category, add screen is opening but when I pushed add I took invalid argument(s) error app is broken. How can ı solve this issue?.
class EmptyCard extends StatelessWidget {
EmptyCard({this.where});
final String where;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: TextButton(
onPressed: (){
if(where=="homeScreen"){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route:where),
);
}
else if(where=="subCategoryScreen"){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Tarif Ekle",route:where),
);
}
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.black12.withOpacity(0.1),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.add_circle_outline_outlined,size: 100,color: Colors.grey.shade400,),
],
),
),
),
);
}
}
class AddMenuScreen extends StatefulWidget {
AddMenuScreen({this.categoryId,this.buttonText, this.route});
final int categoryId;
final String route;
final String buttonText;
static String id="addMenuScreen";
#override
_AddMenuScreenState createState() => _AddMenuScreenState();
}
class _AddMenuScreenState extends State<AddMenuScreen> {
final stickerList= List<String>.generate(23, (index) => "images/sticker$index");
int selectedIndex=-1;
Color _containerForStickersInactiveColor=Colors.white;
Color _containerForStickersActiveColor=Colors.black12;
String chosenImagePath;
String newCategoryName;
int addScreenImageNum;
#override
Widget build(BuildContext context) {
return Material(
child: Container(
color: kColorTheme9,
child: Container(
height: 400,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topRight: Radius.circular(40),topLeft: Radius.circular(40)),
),
child:Padding(
padding:EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
color: kColorTheme2,
borderRadius: BorderRadius.circular(90)
),
child: TextField(
style: TextStyle(
color: Colors.black,
fontFamily:"Graduate",
fontSize: 20,
),
textAlign: TextAlign.center,
onChanged: (value){
newCategoryName=value;
},
decoration: InputDecoration(
border:OutlineInputBorder(
borderRadius: BorderRadius.circular(90),
borderSide: BorderSide(
color: Colors.teal,
),
),
hintText: "Menü ismi belirleyin",
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.2),
fontFamily: "Graduate",
),
),
),
),
SizedBox(height: 20,),
Text(" Yana kadırarak menünüz icin bir resim secin",textAlign: TextAlign.center,
style: TextStyle(fontFamily: "Graduate", fontSize: 12),),
SizedBox(height: 20,),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: stickerList.length,
itemBuilder: (context,index){
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: index == selectedIndex ?
_containerForStickersActiveColor :
_containerForStickersInactiveColor,
),
child:TextButton(
child: Image(
image: AssetImage("images/sticker$index.png"),
),
onPressed: (){
setState(() {
selectedIndex = index;
});
},
),
);
}
),
),
SizedBox(height: 20,),
Container(
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid),
color: kColorTheme7,
borderRadius: BorderRadius.circular(90),
),
child: TextButton(
onPressed: (){
if(widget.route=="homeScreen"){
Navigator.pop(context, ModalRoute.withName(HomeScreen.id));
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>HomeScreen(newCategoryName: newCategoryName,
newCategoryImagePath: "images/sticker$selectedIndex.png")));
}
else if(widget.route=="subCategoryScreen"){
Navigator.pop(context, ModalRoute.withName(SubCategoriesScreen.id));
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>SubCategoriesScreen(categoryId: widget.categoryId,subCategoryName: newCategoryName,
subCategoryImagePath:"images/sticker$selectedIndex.png" )));
}
},
child: Text(widget.buttonText, style: TextStyle(fontSize: 20, color: Colors.white,
fontFamily: "Graduate", fontWeight: FontWeight.bold),),
),
),
],
),
),
),
),
);
}
}
class _SubCategoriesScreenState extends State<SubCategoriesScreen> {
void initState(){
super.initState();
if(widget.categoryId!=null && widget.subCategoryImagePath!=null && widget.subCategoryName!=null){
addSubCategory();
}
}
void addSubCategory(){
SubCategoryModel subCategoryModel=SubCategoryModel(
subCategoryId:widget.categoryId,
subCategoryImagePath: widget.subCategoryImagePath,
subCategoryName: widget.subCategoryName,
categoryColor: Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(0.5));
if(categoryModels!=null){
for (var categoryModel in categoryModels){
if (categoryModel.categoryId == subCategoryModel.subCategoryId){
categoryModel.subCategoryModels.insert(categoryModel.subCategoryModels.length-1,subCategoryModel);
}
}
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: BorderedText(
child:Text(
categoryModels[widget.categoryId].categoryName,
style: TextStyle(
color: Color(0XFFFFFB00),
fontSize: 30,
fontFamily: "Graduate"
),
),
strokeWidth: 5,
strokeColor: Colors.black,
),
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: (){
Navigator.pop(context);
},
iconSize: 40,
color: Color(0xFFA2000B),
),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage("images/cuttedlogo.PNG"),
)
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/logoBGopacity.png"),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.builder(
scrollDirection: Axis.vertical,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount:categoryModels[widget.categoryId].subCategoryModels.length,
itemBuilder: (context,index){
if(categoryModels[widget.categoryId].subCategoryModels[index].subCategoryId==-1){
return EmptyCard(where: "subCategoryScreen");
}
return SubCategoryCard(subCategoryId:widget.categoryId,subcategoryName: categoryModels[widget.categoryId].subCategoryModels[index].subCategoryName,
subCategoryImagePath: categoryModels[widget.categoryId].subCategoryModels[index].subCategoryImagePath,
subCategoryColor: categoryModels[widget.categoryId].subCategoryModels[index].categoryColor,);
}
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid),
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: TextButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(categoryId:widget.categoryId,buttonText: "Tarif Ekle", route:"subCategoryScreen"),
);
},
child: BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text("Tarif Ekle",style: TextStyle(
color: Colors.white,
fontFamily:'Graduate',
fontSize:30,
),
),
),
),
),
),
],
)
],
),
),
),
);
}
}
Error:
======== Exception caught by widgets library =======================================================
The following ArgumentError was thrown building SubCategoriesScreen(dirty, state: _SubCategoriesScreenState#72f75):
Invalid argument(s)
The relevant error-causing widget was:
SubCategoriesScreen file:///C:/Users/yagiz/AndroidStudioProjects/lezzet_kitabi/lib/screens/add_menu_screen.dart:121:98
When the exception was thrown, this was the stack:
#0 List.[] (dart:core-patch/growable_array.dart:254:60)
#1 _SubCategoriesScreenState.build (package:lezzet_kitabi/screens/subCategoriesScreen.dart:61:29)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4742:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4625:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4797:11)

Streambuilder error in SingleChildScrollView flutter

This is the streambuilder wrapped under SingleChildScrollView inside the body of scaffold. Scroll View is not working after streambuilder is placed under SingleChildScrollView. StreamBuilder fetches data from firebase through cloud firestore.
body: Container(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection(
'blogsDatabase/${widget.blogUIDInFirebase}/comments')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
final _commentsFetched = snapshot.data.documents;
List<CommentBubble> _commentBubbleWidget = [];
for (var comment in _commentsFetched) {
_commentBubbleWidget.add(
CommentBubble(
name: comment.data['name'],
comment: comment.data['comment'],
),
);
}
return Expanded(
child: ListView(
children: _commentBubbleWidget
),
);
},
),
),
Container(
margin: EdgeInsets.all(10),
child: Material(
shadowColor: Colors.orange,
child: TextField(
onChanged: (value) {
readerAddComment = value;
},
keyboardType: TextInputType.emailAddress,
decoration:
kRegDetailFieldDeco.copyWith(hintText: 'Add comment'),
),
),
),
FlatButton(
onPressed: () {
if (_nameReader != null &&
widget.readerEmail != null &&
readerAddComment != null) {
Firestore.instance
.collection(
'blogsDatabase/${widget.blogUIDInFirebase}/comments')
.document()
.setData(
{
'name': _nameReader,
'email': widget.readerEmail,
'comment': readerAddComment,
},
);
}
},
child: Text('Add comment')),
],
),
),
),
Comment Bubble Class, it is a stateless widget which will display the comments.
class CommentBubble extends StatelessWidget {
final String name;
final String comment;
CommentBubble({this.name, this.comment});
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(10.0),
child: Text('$name --- $comment'),
);
}
}
Error shown in console
RenderBox was not laid out: RenderRepaintBoundary#dd879 relayoutBoundary=up1 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'
It is Happening Because your Widget Structure due to which error is there is like
-Container
-SingleChildScrollView
-Expanded
-Column
-Expanded
-Expanded
-ListView
Now See This Error Which you are getting , it is saying that it is error regarding the size , Wrap your Column in Some other widget rather than Expanded
It seems that you need space to place your ListView inside the Column().
Remove the Expanded widget, and replace it with Container.
For example:
Container(
height: 100,
child: ListView(
children: _commentBubbleWidget
),)
But, I don't recommend the solution above for you. That's too bad for the UI (just my opinion). Because, you use ListView inside Column. By using this way, you have to decide height of the ListView. Don't forget, the phones' size are vary.
Better to separate the ListView, and place your textfield in BottomNavigationBar.
This is mine:
Scaffold(
appBar: AppBar(
title: textCustom(
'Review ${widget.destination}', Colors.black87, 20, 'Hind'),
leading: IconButton(
icon: Icon(
Icons.arrow_back_ios,
),
onPressed: () {
Navigator.pop(context);
}),
iconTheme: IconThemeData(color: Colors.black87, size: 10),
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: StreamBuilder<QuerySnapshot>(
stream: kategori
.document(widget.kategori)
.collection(widget.subKategori)
.document(widget.docId)
.collection("review")
.orderBy("timeStamp", descending: true)
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('${snapshot.error}');
if (snapshot.data == null)
return Center(
child: textCustom(
'Loading...', Colors.black87, 14, 'Montserrat'));
final review= snapshot.data.documents;
return snapshot.data.documents.isNotEmpty
? ListView.builder(
itemCount: review.length,
itemBuilder: (context, index) {
return Comment(
name: review[index]['name'],
profilePhoto: review[index]['foto'],
comments: review[index]['review'],
date: (review[index]['timeStamp'] != null)
? DateFormat.yMMMd().format(DateTime.parse(
review[index]['timeStamp']
.toDate()
.toString(),
))
: '',
);
})
: Center(child: Text('Empty'));
}),
),
bottomNavigationBar: Padding(
padding: MediaQuery.of(context).viewInsets,
child: BottomAppBar(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: <Widget>[
Expanded(
child: TextField(
controller: textMessageController,
onChanged: (text) {
input = text;
setState(() {
enableButton = text.isNotEmpty;
});
},
textCapitalization: TextCapitalization.sentences,
maxLines: null,
style: TextStyle(
color: Colors.black87,
fontSize: 16,
fontFamily: 'Montserrat'),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: new BorderSide(color: Colors.white),
borderRadius: new BorderRadius.circular(8.0),
),
focusedBorder: OutlineInputBorder(
borderSide: new BorderSide(color: Colors.white),
borderRadius: new BorderRadius.circular(8.0),
),
contentPadding:
EdgeInsets.only(left: 16.0, bottom: 16.0, top: 16.0),
hintText: 'Write some review',
),
)),
SizedBox(
width: 8.0,
),
enableButton
? IconButton(
onPressed: handleSendMessage,
icon: Icon(
Icons.send,
color: Color(0xFFDB5C48),
))
: IconButton(
onPressed: () {},
icon: Icon(
Icons.send,
color: Colors.grey,
))
],
),
),
),
),
);