Stream Cart total price in flutter using firebase backend - firebase

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

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

firebase get some data using where

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

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

Retrieve collection of certain firebase document in flutter

the document name is the auth user but i cant retrive it as index in the firestore i only need to point at the user.uid and retrieve its collection
StreamBuilder(
stream: Firestore.instance.collection("Attendees").snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return new ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
padding: const EdgeInsets.only(top: 5.0),
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.documents[index];
return new Row(
textDirection: TextDirection.ltr,
children: <Widget>[
Expanded(child: Text(ds['absenceDay'])),
Expanded(child: Text(ds['excuse'])),
],
);
});
}
},
)
Try the following:
getDocument() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
return Firestore.instance.collection("Attendees").document(user.uid).snapshots();
}
Then use it in StreamBuilder:
StreamBuilder(
stream: getDocument(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {

Resources