firebase get some data using where - firebase

This is my firebase each group of documents added by different user I want to get the documents based in the userId filed I sored that filed in id variable and that is my code the condition is not working, it gets me all documents in glucose collection
stream: FirebaseFirestore.instance
.collection('glucose')
.where('userId', isEqualTo: id)
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
for (int index = 0;
index < snapshot.data.docs.length;
index++) {
DocumentSnapshot documentSnapshot = snapshot.data.docs[index];
chartData.add(ChartData.fromMap(documentSnapshot.data()));
}

Try the below query, let me know if it works :)
Also, in this case you will probably going to get Map so you can use .map((e) => null).toList() to get them in list and render them using ListView or Column or what ever suits you :)
StreamBuilder(
stream:
FirebaseFirestore.instance.collection('glucose').snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
return ListView(
children: snapshot.data.docs.map(
(singleDoc) {
if (snapshot.data.docs.contains(singleDoc['userID']))
return Card(
child: ListTile(
title: Text(
singleDoc['someFieldHere'],
),
),
);
},
).toList(),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),

Related

when fetching firestore database "itemCount: snapshot.data.documents.length" is not working anymore. does anyone know how to solve this problem?

this is the code:...............
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Practice Firebase"),
),
body: StreamBuilder(
stream:
FirebaseFirestore.instance.collection("Animals").snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: const CircularProgressIndicator.adaptive(),
);
} else {
return ListView.builder(
itemCount: snapshot.data?.documents.length,
itemBuilder: (context, index) {
return ListTile(
title: snapshot.data.documents[index]["name"],
);
});
}
}));
}
}
The getter 'documents' isn't defined for the type 'Object'.
Try importing the library that defines 'documents', correcting the name to the name of an existing getter, or defining a getter or field named 'documents'
You can try to use the code skeleton below (here I have an own class MyAnimal so I can use members instead of map):
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('Animals')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
// handle error
return const Text('Error');
}
if (snapshot.connectionState == ConnectionState.waiting) {
// return progress indicator widget
return const Center(child: CircularProgressIndicator());
}
// here you should get the streamed documents like:
// snapshot.data!.docs
// so to build a ListView for example:
return ListView(
children:
snapshot.data!.docs.map((DocumentSnapshot document) {
final animal = document.data() as MyAnimal;
return ListTile(
title: Text(animal.name!),
);
}).toList(),
);
})
I had the same problem and this fixed it for me. So basically you need to give the snapshot the datatype of AsyncSnapshotsince .docscannot be called on an Object type.
StreamBuilder(
builder: (context, AsyncSnapshot snapshot) {
return ListView.builder(
itemCount: snapshot.data?.docs.length,
just declare the dataType of builder arguments..i mean,
builder:(BuildContext context,AsyncSnapshot snapShot)
enter image description here
Well actually, if you do this - you can access docs and length ...
builder: (BuildContext ctx, AsyncSnapshot LessThanSign QuerySnapshot GreaterThanSign streamSnapShot){}

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]);
},
);
},
),
);

Stream Cart total price in flutter using firebase backend

Please I'm stuck, I'm trying to stream product price from cart and sum up to get the total... here is my code...
Container(
alignment: Alignment.bottomCenter,
child: StreamBuilder(
stream: firebaseFirestoreOperations.usersRef
.doc(firebaseFirestoreOperations.getUserId())
.collection('Cart')
.doc('9oNFPyrUPN9wORFsyqvY')
.snapshots(),
builder: (context, snapshot) {
var price = snapshot.data['price'];
return CartBottomBar(
totalPrice: price,
);
}),
),
Container(
alignment: Alignment.bottomCenter,
child: StreamBuilder(
stream: firebaseFirestoreOperations.usersRef
.doc(firebaseFirestoreOperations.getUserId())
.collection('Cart')
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
let total = 0;
// snapshot.docs.forEach((doc) => {
snapshot.forEach((doc) => {
total += doc.data()['price'];
});
return Text('\$${total} ');
}
return Text('Loading');
}),
),
Check this ref: https://firebase.flutter.dev/docs/firestore/usage#realtime-changes

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']),
),
);
}),
);
});
});
});

Firebase - get firestore Array Data to StreamBuilder Flutter

child: StreamBuilder(
stream: databaseReference
.collection(collectionName)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView(
shrinkWrap: true,
children: elementList(snapshot),
);
}
}
),
this is the my StreamBuilder code,
elementList(AsyncSnapshot<QuerySnapshot> snapshot) {
return snapshot.data.documents.map((document).mydata {
return ListTile()
}).toList();
}
mydata is the document name like Country, and name of array List,
this is the ListTile building code, and I want get the Country list in this StreamBuilder, and elements to ListTile.
the database looks like,
FireStore database Country List in the document in the collection

Resources