I'm trying to fetch my data from firestore - firebase

It does work cus i'm seeing
I/flutter (10071): [{quantity: 7, price: 4, name: Ayam Masah Merak, recipe: Ayam, Chilli, id: c5f935b0-538d-11eb-acb5-4d9f82c74017, category: food, picture: [https://firebasestorage.googleapis.com/v0/b/aizadfyp2021final.appspot.com/o/images%2F2021-01-10%2021%3A49%3A51.509046?alt=media&token=85605972-86da-4747-96ac-baa0abd5fe3a]}]
but at my phone it shows 'no data'. What did I do wrong? the code:
return FutureBuilder(
future: Global.productsRef.getData() , // this one too, yea
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
List<Product> products = snapshot.data;
return GridView.builder( // reload please, amazing
itemCount: products.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return Single_prod(
prod_name: products[index].name,
prod_picture: products[index].picture[0],
prod_price: products[index].price,
product: products[index] ,
);
},
);
} else
return Text('no data');
});

Related

How to retrieve all the Data from Firestore

enter image description here
The Picture above is my Firestore.
I'm trying to retrieve all the data from the Collection UserData.
This is the Code I used. I'm not getting any Red lines or error in Console but its not showing the data of the Collection UserData. Please Help
Container(
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('UserData')
.snapshots(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot book = snapshot.data.docs[index];
return ListTile(
leading: Text(book['title']),
title: Text(book['Date']),
subtitle: Text(book['Time']),
);
},
);
}
)
),

How to retrieve data from Firebase Realtime to the flutter app in a lisview

I am looking to retrieve data stored in Firebase Realtime database and display it in a new page in a lisview, how can I achieve that. So far I can retrieve and print it out in a console terminal.
My code is below:
class BarcodesResultPreviewWidget extends StatelessWidget {
FirebaseDatabase.instance.reference().child('ScannedResults');
body: Column(
children: <Widget>[
previewView,
//printing scanned results
Expanded(
child: ListView.builder(
itemBuilder: (context, position) {
return BarcodeItemWidget(preview.barcodeItems[position]);
},
itemCount: preview.barcodeItems.length,
),
),
FlatButton(
color: Colors.grey,
child: Text('Save',),
onPressed: () {
databaseRef.push().set({
'ScannedItem': preview.barcodeItems
.map((barCodeItem) => barCodeItem.toJson())
.toString(),
});
},
),
To fetch the data into a new page and build listview, try something like this:
return Scaffold(
body: FutureBuilder(
future: databaseRef.once(),
// future: FirebaseDatabase.instance
// .reference()
// .child("ScannedResults")
// .once(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return new Text('Loading....');
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
List scannedItemsValues = [];
snapshot.data.value.forEach(
(_, values) => scannedItemsValues.add(values["ScannedItem"]));
print(scannedItemsValues);
return ListView.builder(
itemCount: scannedItemsValues.length,
itemBuilder: (BuildContext context, int index) {
// build your listView here
print(scannedItemsValues[index]);
return Text(scannedItemsValues[index]);
},
);
},
),
);

Flutter/Dart Stream Builder Multiple Collections Firebase

I know there's probably a better way to do this but would like if its possible, to maintain the current DB structure.. (see attached)
DB Collections
Question: How can I return a StreamBuilder with a Listview(child:listTile) that displays profiles for all UID's that a particular user is following(eg: return user profiles that user "BHRaCBR.." is following). In this case im BHRaCBR...
Code below works but only returns one listTile (user):
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('following')
.doc('BHRaCBR..')
.collection('userFollowing')
.where('isApproved', isEqualTo: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.documents[index];
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('profile')
.where('uid', isEqualTo: ds['uid'])
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
final data0 = snapshot.data.docs;
return Container(
height: 200,
child: ListView.builder(
itemCount: data0.length,
itemBuilder: (BuildContext ctx, index) {
return Card(
child: ExpansionTile(
leading: CircleAvatar(
radius: 32,
backgroundImage: NetworkImage(
data0[index]
.data()['image_url']
.toString(),
),
),
title: Text(data0[index].data()['username']),
),
);
}),
);
});
});
});

can i access the document id using this snapshot call?

This is the streambuilder im using to access all the documents at once
StreamBuilder(
stream: Firestore.instance.collection('projects').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('data is loading');
return ListView.builder(
itemBuilder: (ctx, index) {
return ProjectItem(
id: snapshot.data.documents[index]['id'],
title: snapshot.data.documents[index]['title'],
members: snapshot.data.documents[index]['members'],
complexity: snapshot.data.documents[index]['complexity'],
affordability: snapshot.data.documents[index]['affordability'],
duration: snapshot.data.documents[index]['duration'],
docid: snapshot.data.document[index].documentid,
);
},
itemCount: snapshot.data.documents.length,
}
Can i use docid: snapshot.data.document[index].documentid to access the document ids individually? if not whats the option? Thanks
You can make a custom Object constructor to use data from the document snapshot.
class ProjectItem {
String id;
String title;
String members;
String complexity;
String affordability;
String duration;
String docid;
ProjectItem({....});
factory ProjectItem.fromFirestore(DocumentSnapshot doc) {
return ProjectItem(
id: doc.data['id'],
title: doc.data['title'],
members: doc.data['members'],
complexity: doc.data['complexity'],
affordability: doc.data['affordability'],
duration: doc.data['duration'],
docid: doc.documentID,
);
}
}
And then just use this constructor inside the list view to make the object
return ProjectItem.fromFirestore(
snapshot.data.documents[index]
);
You can get the documentID this way
StreamBuilder(
stream: Firestore.instance.collection('projects').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('data is loading');
return ListView.builder(
itemBuilder: (ctx, index) {
QuerySnapshot snap = snapshot.data; // Snapshot
List<DocumentSnapshot> items = snap.documents; // List of Documents
DocumentSnapshot item = items[index]; Specific Document
return ProjectItem(
id: item.data['id'],
title: item.data['title'],
members: item.data['members'],
complexity: item.data['complexity'],
affordability: item.data['affordability'],
duration: item.data['duration'],
docid: item.documentID, // Document ID
);
},
itemCount: snapshot.data.documents.length,
);
},
),
)
THIS WORKED FOR ME:
StreamBuilder(
stream: Firestore.instance.collection('projects').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('data is loading');
return ListView.builder(
itemBuilder: (ctx, index) {
return ProjectItem(
id: snapshot.data.documents[index]['id'],
title: snapshot.data.documents[index]['title'],
members: snapshot.data.documents[index]['members'],
complexity: snapshot.data.documents[index]['complexity'],
affordability: snapshot.data.documents[index]['affordability'],
duration: snapshot.data.documents[index]['duration'],
docid: snapshot.data.documents[index].documentID,
);
},
itemCount: snapshot.data.documents.length,
);

How to make list view to listview.builder in flutter?

buildComments() {
return StreamBuilder(
stream: commentRef
.document(postId)
.collection('comments')
.orderBy('timestamp', descending: false)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
List<Comment> comments = [];
snapshot.data.documents.forEach((doc) {
print(comments);
comments.add(Comment.fromDocument(doc));
});
return ListView(
children: comments,
);
});
}
I was trying to convert it in list view.builder but it gives me error you can can't use list instead of Widget, Can anyone solve this problem.
You should do the following:
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
contentPadding: EdgeInsets.all(8.0),
title: Text(snapshot.data.documents[index].data["name"]),
);
});
Assuming you have name in the document.

Resources