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

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

Related

The method 'data' was called on null. Receiver: null Tried calling: data() in flutter firebase chat app

The following NoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(dirty, state: _FutureBuilderState<DocumentSnapshot<Map<String, dynamic>>>#c2b0e):
The method 'data' was called on null.
Receiver: null
Tried calling: data()
in chatApp :-
here source code highlighted
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jobkar/public/model/user_model.dart';
import 'package:jobkar/public/view/navigation/message/chat_room.dart';
class Message extends StatefulWidget {
const Message({Key? key}) : super(key: key);
#override
State<Message> createState() => _MessageState();
}
class _MessageState extends State<Message> {
final currentUser = FirebaseAuth.instance.currentUser;
final searchController = TextEditingController();
String search = '';
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 50,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color: Colors.white),
child: Row(
children: [
Flexible(
child: TextFormField(
controller: searchController,
onChanged: (value) {
search = value;
},
decoration: InputDecoration(
hintText: 'Search person',
border: InputBorder.none,
prefixIcon: const Icon(
Icons.dehaze,
size: 26,
color: Colors.black54,
),
hintStyle: GoogleFonts.raleway(
fontSize: 16, fontWeight: FontWeight.normal)),
),
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.black54),
child: Center(
child: IconButton(
onPressed: () {
setState(() {});
},
icon: const Icon(
Icons.search,
color: Colors.white,
),
),
),
),
),
],
),
),
),
Expanded(
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.doc(currentUser!.uid)
.collection('message')
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(
color: Colors.blue[900],
),
);
} else if (snapshot.hasError) {
return const Center(
child: Text("Something went wrong please try later"),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
var friendId = snapshot.data!.docs[index].id;
var lastMessage = snapshot.data!.docs[index]['lastMessage'];
return FutureBuilder(
future: FirebaseFirestore.instance.collection('users').doc(friendId).get(),
builder: (BuildContext context , AsyncSnapshot snapshot) {
**final userModel = UserModel.fromMap(snapshot.data.data() as Map<String,dynamic>);**
if (snapshot.hasData) {
var friend = snapshot.data;
if (search.isEmpty) {
return ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
ChatRoom(
userModel: userModel,
friendName: friend['name'],
friendImage: friend['imageUrl'],
friendId: friend['uid'],
friendEmail: friend['email']
),
),
);
},
title: Text(
friend['name'],
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
subtitle: Text(lastMessage,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
} else if (friend['name']
.toString()
.toLowerCase()
.startsWith(search.toLowerCase()) ||
friend['name']
.toString()
.toUpperCase()
.startsWith(search.toUpperCase())) {
return ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
ChatRoom(
userModel: userModel,
friendName: friend['name'],
friendImage: friend['imageUrl'],
friendId: friend['uid'],
friendEmail: friend['email']
),
),
);
},
title: Text(
friend['name'],
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
subtitle: Text(lastMessage,
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
}
return Container();
}
return Container();
}
);
});
}
return Container();
},
),
),
],
),
);
}
}
Generate the model after getting data like
builder: (BuildContext context , AsyncSnapshot snapshot) {
if (snapshot.hasData) {
final mapData = snapshot.data.data() as Map?;
if(mapData == null) return Text("Got null data");
final userModel = UserModel.fromMap(mapData);
var friend = snapshot.data;

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

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

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?

How to sent data into two different class within a file using navigator in flutter

I am lost my direction. Can Someone help me how can I send my data from the first page to the second page using Navigator? There are two types of class that exist in the destination file which are a stateful widget and a stateless widget. I am trying to send data from the first page using navigator:
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW(category :categoriesList[index].name)));
The restaurantLISTVIEW is a stateful class on the second page. How can I share the data with the stateless class within the same file?
My full code on the first page:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:phpfood/restaurantlist.dart';
//import 'globals.dart' as globals;
import 'custom_textW.dart';
class Category {
final String name;
final String image;
Category({#required this.name, #required this.image});
}
List<Category> categoriesList = [
Category(name: "Breakfast", image: "nasilemak.png"),
//Category(name: "Kuih", image: "kuih.png"),
Category(name: "Lunch", image: "lunch.png"),
//Category(name: "Minum Petang", image: "mnmptg.png"),
Category(name: "Dinner", image: "mknmlm.png"),
//Category(name: "Minum Malam", image: "mnmmlm.png"),
//Category(name: "Minuman", image: "air.png"),
];
class Categories extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 120,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categoriesList.length,
itemBuilder: (_, index) {
return Padding(
padding: const EdgeInsets.only(left: 28.0, top: 8),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(color: Colors.white, boxShadow: [
BoxShadow(
color: Colors.red[200], offset: Offset(4, 6), blurRadius: 20)
]),
//tambah di sini kalau nk gesture
child: InkWell(
//onTap: ()=> Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(),)),
onTap: (){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW(category :categoriesList[index].name)));
},
/*{
if(categoriesList[index].name == "Breakfast"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW(category: 'breakfast')));
//Navigator.of(context).push(MaterialPageRoute<void>(builder: (context) => restaurantLISTVIEW(category: 'breakfast',),),);
}
else if(categoriesList[index].name == "Lunch"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW()));
}
else if(categoriesList[index].name == "Dinner"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new restaurantLISTVIEW()));
}
},*/
child: Image.asset(
"images/${categoriesList[index].image}",
width: 100,
),
),
),
SizedBox(
height: 5,
),
CustomText(
text: categoriesList[index].name,
size: 17,
colors: Colors.black,
)
],
),
);
},
),
);
}
}
My full code on the second page:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'breakfast.dart';
// ignore: camel_case_types
class restaurantLISTVIEW extends StatefulWidget {
restaurantLISTVIEW({this.category});
final String category;
#override
_restaurantLISTVIEWState createState() => _restaurantLISTVIEWState();
}
// ignore: camel_case_types
class _restaurantLISTVIEWState extends State<restaurantLISTVIEW> {
Future<List> getData() async{
var url = 'http://10.0.2.2/foodsystem/restaurantlist.php';
var data = {'product_type': 'xde pape ppon saje nk hantar value'};
var response = await http.post(url, body: json.encode(data));
//final response= await http.get("http://10.0.2.2/foodsystem/getdata.php");
return json.decode(response.body);}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
//Text("Restaurant's Owner Page"),
Text('${widget.category}', textAlign: TextAlign.center, style: TextStyle(fontSize: 25, fontWeight: FontWeight.w700), ),
],
),
centerTitle: false,
//automaticallyImplyLeading: false,
),
body:
Padding(
padding: const EdgeInsets.only(bottom: 20, left: 5, right: 5),
child: Column(
children: [
SizedBox(height: 30,),
Container(
//decoration: BoxDecoration(border: Border.all(color: Colors.black, width: 4), borderRadius: BorderRadius.circular(15)),
height: 600,
child: FutureBuilder<List>(
future: getData(),
builder: (context, snapshot){
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData ?
ItemList(list: snapshot.data,) :
Center(child: CircularProgressIndicator(),);
},
),
),
FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(
'${widget.category}'
),
);
},
);
},
),
SizedBox(height: 10,),
],
),
),
);
}
}
class ItemList extends StatelessWidget {
final List list;
final String category;
ItemList({this.list, this.category});
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Container(
//color: Colors.red.shade100,
height: 600,
child: ListView.builder(
itemCount: list==null ? 0 : list.length,
itemBuilder: (context, i){
return new Container(
height: 200,
child: new GestureDetector(
onTap: ()
{Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(list: list, index: i, category: category,)));},
/*{
if(category == "Breakfast"){
Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context)=> new SarapanPagi(list: list, index: i, category: category,)));
}
},*/
child: new Card(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FloatingActionButton(
onPressed: (){
return showDialog(
context: context,
builder: (context){
return AlertDialog(
content: Text(
'$category hellp'
),
);
},
);
},
),
Row(
children: [
Container(
constraints: BoxConstraints(minWidth: 180, maxWidth: 180),
child:
Column(
children: [
Text(list[i]["restaurant_name"], style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), textAlign: TextAlign.center,),
Text("Restaurant ID: ${list[i]["restaurant_id"]}", style: TextStyle(fontSize: 20,), textAlign: TextAlign.center,),
],
),
),
Padding(
padding: const EdgeInsets.only(left :20.0),
child: Container(
constraints: BoxConstraints(minWidth: 150, maxWidth: 300),
child:
SizedBox(
width: 50,
child: Column(
children: [
Text("SSM: ${list[i]["restaurant_ssm"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 15),),
Text("Phone: ${list[i]["restaurant_phone"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 15),),
Text("Address: ${list[i]["restaurant_address"]}", textAlign: TextAlign.center, style: TextStyle(fontSize: 15),),
],
),
),
),
),
],
),
Row(
children: [
],
),
],
),
),
),
);
},
),
),
);
}
}
As you can see in the stateless class, I am already calling the value from the first page, but it returns null because there is nothing forwarded to that class.
The problem is that you did not share the name data for the ItemList class through the category parameter:
make the following correction:
builder: (context, snapshot){
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData ?
ItemList(list: snapshot.data, category: widget.category) :
Center(child: CircularProgressIndicator(),);
},
a tip is to use the #required notation in the widget constructor so as not to forget to fill in the named parameters. Example:
class ItemList extends StatelessWidget {
final List list;
final String category;
ItemList({#required this.list, #required this.category});
#override
Widget build(BuildContext context) {
return Container();
}
}

Flutter Firebase: not able update Database

I want to update my Collection with an NumberPicker in a Alert Dialog. I do not get any errors in code or from the emulator. When i press the button to update the code the terminal do not give any errors. Everything looks fine but for some reason i do not work. When you need more Information just leave a comment with what you excactly need. :)
import 'package:flutter/material.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:testapp/services/Services.dart';
import 'models/Goals.dart';
class Statistics extends StatefulWidget {
#override
_StatisticsState createState() => _StatisticsState();
}
class _StatisticsState extends State<Statistics> {
int _currentFirstValue = 1;
int totalFirst;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: 260,
child: StreamBuilder(
stream: FirestoreService().getGoals(),
builder: (context, AsyncSnapshot<List<Goal>> snapshot) {
if (snapshot.hasError || !snapshot.hasData) {
return Center(child: CircularProgressIndicator(
backgroundColor: Color(0XFF1954A1),
));
}
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 1,
itemBuilder: (BuildContext context, int index) {
// ignore: missing_return
Goal goal = snapshot.data[index];
return Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
margin: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
height: 230,
width: 350,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.grey[300],
offset: const Offset(0.5, 1),
blurRadius: 4.0,
spreadRadius: 0.1,
),
]),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text('WeekGoals', style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w500,
),),
SizedBox(width: 100),
SizedBox(
height: 20,
width: 87,
child: FlatButton(
child: Text('edit', style: TextStyle(
fontSize: 17,
color: Colors.yellow[700]
),),
onPressed: () {
return showDialog(
context: context,
barrierDismissible: true,
builder: (context) => AlertDialog(
content: Column(
children: <Widget>[
Text('weekly goals'),
NumberPicker.integer(
initialValue: _currentFirstValue,
minValue: 1,
maxValue: 100,
onChanged: (newGoal) => setState(() => {
_currentFirstValue = newGoal,
totalFirst = _currentFirstValue,
})
),
Row(
children: <Widget>[
RaisedButton(
child: Text('edit goals'),
onPressed: () async {
Goal goal = Goal(
weekActivityGoal: totalFirst,
);
await FirestoreService().updateGoal(goal);
Navigator.pop(context, false);
},
),
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.pop(context, false);
},
)
],
)
],
),
)
);
},
),
)
],
),
SizedBox(height: 10),
Row(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 17.5),
child: CircularPercentIndicator(
header: Text('activitys', style: TextStyle(
fontSize: 17,
),),
radius: 130,
progressColor: Colors.red,
lineWidth: 8,
backgroundColor: Colors.grey[200],
percent: goal.weekActivity*100/goal.weekActivityGoal,
center: Text('${goal.weekActivity}/${goal.weekActivityGoal}'),
),
),
],
),
],
),
),
],
);
});
}),
),
);
}
}
Here this has been helping a lot of people try i out might help you too.
StreamBuilder(
stream: Firestore.instance.collection('Hearings').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Select lot');
case ConnectionState.waiting:
return Text('Awaiting bids...');
case ConnectionState.active:
{
print('active');
return Text('${snapshot.data}');
}
case ConnectionState.done:
{
print('Done');
return _buildList(context, snapshot.data);
}
}
return null;
}),
));
}
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
padding: const EdgeInsets.only(top: 20.0),
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () => Firestore.instance.runTransaction((transaction) async {
final freshSnapshot = await transaction.get(record.reference);
final fresh = Record.fromSnapshot(freshSnapshot);
await transaction
.update(record.reference, {'votes': fresh.votes + 1});
}),
),
),
);
}
}
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
#override
String toString() => "Record<$name:$votes>";
}
This is where the link this info came from.