check firestore has document or not using Future Builder - flutter

Full code
class yourBookings extends StatefulWidget {
#override
_yourBookingsState createState() => _yourBookingsState();
}
class _yourBookingsState extends State<yourBookings> {
StateModel appState;
bool _loadingVisible = false;
#override
Widget build(BuildContext context) {
appState = StateWidget.of(context).state;
final number = appState?.user?.number ?? '';
Future getPosts() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore
.collection("confirmed_c_rides2")
.document(number)
.collection("1")
.getDocuments();
return qn.documents;
}
return Scaffold(
appBar: AppBar(
title: Text("Your Bookings :"),
),
body: Container(
child: FutureBuilder(
future: getPosts(),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text("Loading ..."),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
Widget image_carousel = new Container(
height: 200.0,
child: new Carousel(
//borderRadius: BorderRadius.all(Radius.circular(2.0)),
boxFit: BoxFit.fitHeight,
images: [
Image.network(
"${snapshot.data[index].data["driverImage"]}"),
Image.network(
"${snapshot.data[index].data["carImage"]}")
],
autoplay: true,
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(milliseconds: 1000),
dotSize: 4.0,
indicatorBgPadding: 6.0,
dotBgColor: Colors.transparent,
),
);
return Card(
child: ListTile(
title: Column(
children: <Widget>[
SizedBox(height: 10),
Text(
"Status: ${snapshot.data[index].data["status"]}",
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
image_carousel,
Text(
"Name: ${snapshot.data[index].data["driverName"]}"),
SizedBox(height: 10),
Text(
"Gender: ${snapshot.data[index].data["gender"]}"),
SizedBox(height: 10),
Text(
"Experience: ${snapshot.data[index].data["experience"]}"),
SizedBox(height: 10),
Text(
"Number: ${snapshot.data[index].data["driverNumber"]}"),
SizedBox(height: 10),
Text(
"Time: ${snapshot.data[index].data["time"]}"),
SizedBox(height: 10),
Text(
"Scheduled on: ${snapshot.data[index].data["rideOn"]}"),
SizedBox(height: 10),
RaisedButton(
color: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => new issue()));
},
child: Text(
"Having issue",
style: TextStyle(color: Colors.white),
),
),
SizedBox(height: 10),
RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => rating1()));
},
child: Text("Rate driver"),
)
],
),
),
);
});
} else if (snapshot==null) {
return Center(
child: Text("not found..."),
);
}
return Center(
child: Text("not found 2..."),
);
}),
),
);
}
}
getPosts() refers to the firestore location for fetching data.
I want to check whether firestore contains number or not as a document using Future Builder.How can i do that?
number -> 1 contains further details.
If number does not exists then show data from firestore else show "not found...".How can i do that?
Future builder is used to stream firestore.

Related

Flutter - Dropdown not changing display when value is changed

When I am changing the value of a dropdown, it does not display the new value.
I am using two documents.
One is containing only a String field.
In the second document, I have a lot of fields.
I have tried different options, but it is not working properly.
Below, you will find the code I am using, it will be easier to understand.
My project is stuck because I am not finding the solution. I will be late on planning if I do not solve this.
If someone can help, it will be highly appreciated. Thank you
Widget MyBody() {
return Column(
children: [
Container(
height: MediaQuery.of(context).size.height / 1.4,
width: MediaQuery.of(context).size.width,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('goals')
.orderBy('goal_Name', descending: false)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
QuerySnapshot data = snapshot.requireData;
return ListView.builder(
itemCount: data.size,
itemBuilder: (context, index) {
DocumentSnapshot document = snapshot.data.docs[index];
selectedFocus = document['area_of_focus_Name'] ;
String idFocus = document['area_of_focus_id'];
test.add(document['area_of_focus_Name']);
print(test);
return Wrap(
children: [
Container(
height: 210,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(
40)),
child: Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.blue, width: 3),
borderRadius: BorderRadius.all(
Radius.circular(45))
),
child: SwipeActionCell(
key: ObjectKey(document['goal_Name']),
trailingActions: <SwipeAction>[
SwipeAction(
title: "delete",
onTap: (
CompletionHandler handler) {
CollectionReference users = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance
.currentUser.uid)
.collection('goals');
users
.doc(document.id)
.delete()
.then((value) =>
print("Goal Deleted"))
.catchError((error) =>
print(
"Failed to delete Goal: $error"));
},
color: Colors.red),
],
child: Padding(
padding: const EdgeInsets.all(0.0),
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
minWidth: leadingIconMinSize,
minHeight: leadingIconMinSize,
maxWidth: leadingIconMaxSize,
maxHeight: leadingIconMaxSize,
),
child: Padding(
padding: const EdgeInsets.only(
top: 16.0),
child: IconButton(
icon: Icon(Icons.edit),
onPressed: () {
//EDIT CONTEXT
//print (document['area_of_focus_Name']);
showDialog(
context: context,
barrierDismissible: true,
builder: (
BuildContext context) {
return AlertDialog(
title: Text("Edit Goal"),
content:
TextFormField(
initialValue: document['goal_Name'],
onChanged: (value) {
setState(() {_newGoalName = value;
});
},
),
actions: <Widget>[
TextButton(
child: Text("OK"),
onPressed: () {
setState(() {
var contextRecordID = (document.id);
FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth
.instance
.currentUser
.uid)
.collection('goals')
.doc(
contextRecordID)
.update(
{
'goal_Name': _newGoalName,
});
});
Navigator.of(context).pop(true);
},
),
//OK Button
TextButton(
child: Text(
"Cancel"),
onPressed: () {
Navigator.of(context).pop(false);
},
),
//Cancel Button
],
);
});
}
),
),),
// trailing: IconButton(icon: Icon(Icons.keyboard_arrow_right),),
title: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child:
Text(
//'goal_Name' correspond au nom du champ dans la table
document['goal_Name'],
style: TextStyle(fontSize: 20,
fontWeight: FontWeight.bold),
maxLines: 6,
overflow: TextOverflow.ellipsis,
),
)
],
),
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('area_of_Focus')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData)
const Text("Loading.....");
else {
List<DropdownMenuItem> focusItems = [];
for (int i = 0; i < snapshot.data.docs.length; i++) {
DocumentSnapshot snap = snapshot.data.docs[i];
focusItems.add(
DropdownMenuItem(
child: Text(
snap['area_of_Focus_Name'], //OK
style: TextStyle(color: Colors.black),
),
value: (snap['area_of_Focus_Name']),
),
);
}
return Row(
children:<Widget> [
DropdownButton(
items: focusItems,
onChanged: (focusValue) {
setState(() {
selectedFocus = focusValue;
});
},
value: selectedFocus,
isExpanded: false,
hint: SizedBox(
width:MediaQuery.of(context).size.width*0.6,
height: 40.0,
child: Text( document['area_of_focus_Name'],//taskAreaFocus,
style: TextStyle(color: Colors.black),// (0xff29B6F6)),
),
),
)]);
}
return Container(
height: 0,width: 0,
);
}),
),
/* MyApp()*/
],
),
),
),
),
),
),
]
);
});
}
}))
]);
}

Flutter & Firebase Error displaying an document (Array) from firebase on a view

I am using FireBase to store some data. So far, I was creating several collections.
But, I have understood that more collections I have more Firebase will cost when the application will be in production. Someone told me that I should create a 'General' collection, where I can store several documents in array. I just want to display on several cards, all the contexts of the array "context_Name"
So I have modify my collections and document, but I do not know how to get the same results as before I modify my code.
The error I am getting is type 'List' is not a subtype of type 'String'.
When the exception was thrown, this was the stack:
#0 _Context_List_Sate.build.. (package:lt/Views/Lists/14_contexts_lists_page.dart:217:45)
#1 MappedListIterable.elementAt (dart:_internal/iterable.dart:412:31)
#2 ListIterator.moveNext (dart:_internal/iterable.dart:341:26)
#3 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:188:27)
#4 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
If i understand the error, I do not find how to fix that while displaying all the records, but one by one on a card. Many thanks for your help.
class Context_List_View extends StatefulWidget {
Context_List_View({Key key}) : super(key: key);
#override
_Context_List_Sate createState() => _Context_List_Sate();
}
class _Context_List_Sate extends State<Context_List_View> {
#override
Widget build(BuildContext context) {
void showAddNote() {
TextEditingController _noteField = new TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return CustomAlertDialog(
content: Container(
width: MediaQuery.of(context).size.width / 1.3,
height: MediaQuery.of(context).size.height / 4,
child: Column(
children: [
TextField(
controller: _noteField,
maxLines: 4,
decoration: InputDecoration(
border: const OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.black, width: 1.0),
),
),
),
SizedBox(height: 10),
Material(
elevation: 5.0,
borderRadius: BorderRadius.circular(25.0),
color: Colors.white,
child: MaterialButton(
minWidth: MediaQuery.of(context).size.width / 1.5,
onPressed: () {
Navigator.of(context).pop();
CollectionReference users = FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('general');
users
.add({'context_Name': _noteField.text,})
.then((value) => print("User Document Added"))
.catchError((error) =>
print("Failed to add user: $error"));
},
padding: EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 15.0),
child: Text(
'Add Context',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
)
],
),
),
);
});
}
return Scaffold(
appBar: new AppBar(
title: new Text('Contexts'),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.add_circle_outline,
color: Colors.white,
),
onPressed: () {
showAddNote();
},
),
],
),
drawer: MyMenu(),
backgroundColor: Colors.white,
body: Column(
children: [
Container(
height: MediaQuery.of(context).size.height /1.4,
width: MediaQuery.of(context).size.width,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('general')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: snapshot.data.docs.map((document) {
return Wrap(
children: [Card(
child: SwipeActionCell(
key: ObjectKey(document['context_Name']),
trailingActions: <SwipeAction>[
SwipeAction(
title: "delete",
onTap: (CompletionHandler handler) {
CollectionReference users = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('contexts');
users
.doc(document.id)
.delete()
.then((value) => print("Context Deleted"))
.catchError((error) => print(
"Failed to delete Next Action: $error"));
},
color: Colors.red),
],
child: Padding(
padding: const EdgeInsets.all(0.0),
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
minWidth: leadingIconMinSize,
minHeight: leadingIconMinSize,
maxWidth: leadingIconMaxSize,
maxHeight: leadingIconMaxSize,
),
child: Image.asset('assets/icons/tag.png'),
),
trailing: IconButton(icon: Icon(Icons.edit), onPressed: ()
{
//EDIT CONTEXT
showDialog(
context: context,
barrierDismissible: true,
builder: (BuildContext context){
return AlertDialog(
title: Text("Edit Context"),
content:
TextFormField(
initialValue: document['context_Name'],
onChanged: (value) {
setState(() {
_newContextName = value;
});
},
),
actions: <Widget>[
FlatButton(
child: Text("OK"),
onPressed: (){
setState(() {
var contextRecordID = (document.id);
FirebaseFirestore.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('general')
.doc(contextRecordID)
.update({
'context_Name':_newContextName,
});
});
Navigator.of(context).pop(true);
},
),//OK Button
FlatButton(
child: Text("Cancel"),
onPressed: (){
Navigator.of(context).pop(false);
},
),//Cancel Button
],
);
});}),
title: Text(
document['context_Name'],
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
),
),
),
]
);
}).toList(),
);
}),
),
],
),
// bottomNavigationBar: ,
);
}
}
You need to iterate over the members of the context_Name field instead of iterating over the entire general collection. Change the beginning of the StreamBuilder to the following:
// ... other code
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('general')
.doc('baceZyyYUciEGGADfgOv')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children:
(snapshot.data.get('context_Name') as List<String>)
.map((contextName) {
return Wrap(children: [
Card(
child: SwipeActionCell(
key: ObjectKey(contextName),
// ... other code
You will also have to update the callbacks to the SwipeActions and AlertDialog as the document variable will no longer exists. Also, change
title: Text(
document['context_Name'],
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
to
title: Text(
contextName,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
(towards the end of the code).

Error GlobalKey Flutter Detected, How solve?

after a few weeks of using Flutter CRUD I was running normally and able to enter the database, but this time I encountered an error as shown below.
The error appears when I finish editing data, delete data. What do you think the solution to this problem is, friends?
Here I provide a snippet of my source code
listnasabah.dart
class ListNasabah {
ApiService apiService;
ListNasabah({this.apiService});
void getNasabah() {
apiService.getNasabah().then((nasabah) {
print(nasabah);
});
}
Widget createViewList() {
return SafeArea(
child: FutureBuilder(
future: apiService.getNasabah(),
builder: (BuildContext context, AsyncSnapshot<List<Nasabah>> snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
'Something wrong with message: ${snapshot.error.toString()}',
textAlign: TextAlign.center,
),
);
} else if (snapshot.connectionState == ConnectionState.done) {
List<Nasabah> nasabah = snapshot.data;
return nasabahListView(nasabah);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Widget nasabahListView(List<Nasabah> listnasabah) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
Nasabah nasabah = listnasabah[index];
return Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
nasabah.nama_debitur,
style: Theme.of(context).textTheme.bodyText1,
),
Text(nasabah.alamat),
Text(nasabah.no_ktp),
Text(nasabah.no_telp),
Text(nasabah.no_selular),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ElevatedButton.icon(
onPressed: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Hapus Data Nasabah'),
content: Text(
'Apakah anda yakin ingin menghapus data nasabah ini?'),
actions: [
TextButton(
child: Text('Yes'),
onPressed: () async {
apiService
.deleteNasabah(nasabah.id)
.then((value) => Navigator.of(
context)
.pushReplacement(
MaterialPageRoute(
builder: (context) =>
DataNasabah())));
})
],
),
);
},
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
icon: Icon(Icons.delete),
label: Text('Hapus'),
),
SizedBox(
width: 5,
),
ElevatedButton.icon(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailNasabah(
nasabah: nasabah,
),
),
);
},
icon: Icon(Icons.navigate_next),
label: Text(
'Detail',
),
)
],
)
],
),
),
),
);
},
itemCount: listnasabah.length,
),
);
}
}

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.