If you want to get a list of users,
just set Firestore.instance.collection("users").snapshots() to the Futurebuilder's future:
But, how can I use userDataRef() to get user's data based on userId using FutureBuilder?
Future<Stream<DocumentSnapshot>> userDataRef() async {
final FirebaseUser user = await auth.currentUser();
return Firestore.instance
.collection("users")
.document(user.uid).snapshots();
}
This is my FutureBuilder.
trying to display users favorite foods.
FutureBuilder(
future: Database.shared.userDataRef(),
builder: (BuildContext context, snapshot) {
if (!snapshot.hasData) {
return Text("Error");
}
final doc = snapshot.data.documents;
final List favoriteFoods = doc["favorite_foods"];
return Text(favoriteFoods.toString());
},
Any advice will be appreciated.
Thanks.
You can use nested FutureBuilder's like this :
Widget nestedFutureBuilders(){
return FutureBuilder(
future: YourFirstRequest,
builder: (BuildContext context, AsyncSnapshot<String> snapshotOne) {
switch (snapshotOne.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshotOne.hasError)
return Text('Error: ${snapshotOne.error}');
return FutureBuilder<String>(
future: YourSecondRequest, // which is related the first request data (snapshotOne.data).
builder: (BuildContext context, AsyncSnapshot<String> snapshotTwo) {
switch (snapshotTwo.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshotTwo.hasError)
return Text('Error: ${snapshotTwo.error}');
return BuildYourUIHere();// you have both data here(snapshotOne.data & snapshotTwo.data)
}
return null; // unreachable
},
);
}
return null; // unreachable
},
);
}
Related
I've got the following code from https://pub.dartlang.org/packages/cloud_firestore#-readme-tab-, but I'm not sure how to get each document's key. What I want to do is tap on each term to view or got to an edit page.
Firestore data model:
-content
--sPuJxAJu0dBMZLBTakd4
---term
---body content
Code:
class _TermsState extends State<Terms> {
#override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('content').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading...');
default:
return ListView(
children:
snapshot.data.documents.map((DocumentSnapshot document) {
print(document['term']);
return ListTile(
title: Text(document['term']),
);
}).toList(),
);
}
},
);
}
}
When you have a DocumentSnapshot, you can use document.documentID to get its key and document.reference.path to get the whole path.
DocumentSnapshot.documentID
DocumentSnapshot.reference returns the DocumentReference for this snapshot, which can be used to (also) get the documentID and also the complete path of the document.
DocumentReference.documentID
DocumentReference.path
In this case document is an object of type DocumentSnapshot, which you already retrieve correctly.
An update to the above answer from creativecreatorormaybenot, the document ID can now be found in document.id from DocumentSnapshot. document.documentID will not return the id.
Here's a link to the answer I found
In my application i want call data from firebase different collections. First I want to list all items and take the id.
Using that id i want to retrieve price from price collection. After that i want to retrieve data from discount. for taking discount.
Here i am using loops.
In the below code the output is coming. First loading list after that it calling second collection price.
Any one know the solution.
I want to listen for calling three collection. Because if any data change i want to update.
#override
void initState() {
super.initState();
_loadItems();
}
Future _loadItems() async {
int price;
int discount;
//calling first collection for getting id and name
firestore.collection("item").snapshots().listen((itemData)async{
for(int i=0;i<itemData.documents.length;i++){
// calling second collection for getting price
firestore.collection("price").where("id",isEqualTo: itemData.documents[i].data["id"])
.snapshots().listen((priceData) async{
price=priceData.documents[0].data['price'];
debugPrint("price showing before loading:"+price.toString());
//calling third collection for getting discount
firestore.collection("discount")
.where("id",isEqualTo: itemData.documents[i].data["id"])
.snapshots().listen((discountData) async{
for(int j=0;j<discountData.documents.length;j++){
discount=discountData.documents.data['discount'];
}
});
});
setState(() {
debugPrint("price showing after loading:"+price.toString());
this.documents.add(new CartProduct(
name:itemData.documents[i].data["id"],
label:itemData.documents[i].data["label"],
price:price,
discount:discount
));
});
}
});
}
Present output
price showing after loading:0
price showing after loading:0
price showing after loading:0
price showing before loading:10.0
price showing before loading:10.0
price showing before loading:10.0
Expected output
price showing before loading:10.0
price showing before loading:10.0
price showing before loading:10.0
price showing after loading:10.0
price showing after loading:10.0
price showing after loading:10.0
I thing you can use nested StreamBuilder's
Widget getTripleCollectionFromFirebase() {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection("item").snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return Text("Error: ${snapshot.error}");
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text("No data, yet.");
case ConnectionState.waiting:
return Text('Loading...');
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.data == null) {
return Text("No record");
} else {
// Do your staff after first query then call the other collection
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection("price")
.where("id", isEqualTo: "fill_it_with_your_code")
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return Text("Error: ${snapshot.error}");
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text("No data, yet.");
case ConnectionState.waiting:
return Text('Loading...');
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.data == null) {
return Text("No record");
} else {
// do your staff after second Query
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection("discount")
.where("id", isEqualTo: "something")
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError)
return Text("Error: ${snapshot.error}");
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text("No data, yet.");
case ConnectionState.waiting:
return Text('Loading...');
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.data == null) {
return Text("No record");
} else {
// do your staff after third Query
// return the widget which you want to build when all data comes.
}
}
},
);
}
}
},
);
}
}
},
);
}
This is my code. I will explain it step by step so you can convert it to your's.
buildUserActions returns a StreamBuilder that StreamBuilder takes all documents which is in actions collection in cloud firestore. When ConnectionState is active, or done if I have data I assign it to variable named _lastActionDocuments.
QuerySnapshot _lastActionDocuments;
Stream<String> streamOfFillActionFields;
Widget buildUserActions() {
return StreamBuilder(
initialData: _lastActionDocuments,
stream: Firestore.instance.collection('actions').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasError)
return Center(child: Text('Error: ${snapshot.error}'));
if (!snapshot.hasData) return Text('No data finded!');
_lastActionDocuments = snapshot.data;
streamOfFillActionFields = fillActionFields();
return reallyBuildActions();
}
},
);
}
then I have a Stream function
Stream<String> fillActionFields() async* {
try {
List<ActionModel> newActionList = [];
for (DocumentSnapshot actionSnapshot in _lastActionDocuments.documents) {
var currentAction = ActionModel.fromSnapshot(actionSnapshot);
// I awaiting to get and fill all data.
await currentAction.fillAllFields();
newActionList.add(currentAction);
}
actionList = newActionList;
// what I yield is not important this case
yield 'data';
} catch (e) {
print(e);
yield 'nodata';
}
}
currentAction.fillAllFields basicly that function ask to firebase to get the related data to fill all fields in my Action Object.
Future<void> fillAllFields() async {
DocumentSnapshot ownerSnapshot = await ownerRef.get();
owner = UserModel.fromSnapshot(ownerSnapshot);
DocumentSnapshot routeSnapshot = await routeRef.get();
route = RouteModel.fromSnapshot(routeSnapshot);
}
then I have another widget which is returning a StreamBuilder. this widget build the real UI widget(buildAllActions) after all data arrived from reference calls.
Widget reallyBuildActions() {
return StreamBuilder(
stream: streamOfFillActionFields,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.data == 'data') {
return buildAllActions();
} else {
return Center(
child: Column(
children: <Widget>[
CircularProgressIndicator(),
Text('Data Loading...')
],
),
);
}
}
},
);
}
I have got answer Use StreamSubscription and call one by one. First I run one loop and check whether it is completed or not than after only call second loop. It working fine but taking delays. when I using StreamBuilder it not completing the request. I don't know why it happening. My code is shown below.
StreamSubscription<QuerySnapshot> streamSub1;
StreamSubscription<QuerySnapshot> streamSub2;
StreamSubscription<QuerySnapshot> streamSub3;
var list = new List();
_loadItems() {
int price;
int discount;
int count =1;
//calling first collection for getting id and name
streamSub1= firestore.collection("item").snapshots().listen((itemData)async{
for(int i=0;i<itemData.documents.length;i++){
list.add(id:itemData.documents[0].data['id'],name:itemData.documents[0].data['id');
if(onFavData.documents.length==productCount){
debugPrint("loop completed");
_loadPrice();
}
}
});
}
void _loadPrice(){
streamSub1.cancel();
int count =1;
for(int i=0;i<list.length;i++){
streamSub2= firestore.collection("price").where("id",isEqualTo: itemData.documents[i].data["id"])
.snapshots().listen((priceData) async{
list[i].price= priceData['price'];
if(count==list.length){
debugPrint("loop completed");
_loadDiscount();
}
});
}
}
_loadDiscount();{
streamSub2.cancel();
int count =1;
for(int i=0;i<list.length;i++){
streamSub3= firestore.collection("price").where("id",isEqualTo: itemData.documents[i].data["id"])
.snapshots().listen((priceData) async{
list[i].discount= priceData['price'];
if(count==list.length){
debugPrint("loop completed");
}
});
}
}
How to get X value from FutureBuilder?
final url = FutureBuilder<List<Url>>(
future: getUrlFromCache(),
builder: (context,snapshot){var x = snapshot.data[1].uniform_resource_locator;},
);
I think using 'x' will cause 'x' always will be equal to 'null'. It is possible to return it dynamically this way:
return ListTile(
title: FutureBuilder(
future: pair,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text( snapshot.data.title);
} else {
return Text( 'Loading...');
}
},
),
);
FutureBuilder always returns Widget type. Put your functionality inside the FutureBuilder.
In my case it returns Text widget. It is assigned to 'title:' and dynamically displayed on the screen as a ListTile.
Just replace the Text widget with the required widget that will use the data.
check this out : FutureBuilder
you can initilaize a global variable then assign a value inside the FutureBuilder but I dont know it's a good aproach doing this inside FutureBuilder.
// instead of creating dynamic types try to create static types.
var x;
FutureBuilder<String>(
future: _calculation, // a previously-obtained Future<String> or null
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
x = snapshot.data[1].uniform_resource_locator;
return Text('Result: ${snapshot.data}');
}
return null; // unreachable
},
)
I'm trying to figure out a way to indicate to a surrounding class when the FutureBuilder is done loading. RefreshIndicator takes a Future as a parameter and stops showing the refresh indicator when the Future completes. I don't have access to the exact same Future variable that's being passed to the FutureBuilder, especially when these are in two separate classes, unless I can pass a reference to one and when it completes in the other class, I'll know...
I'm searching for this answer too. Finally i figured it out...
Here is how i done
FutureBuilder<String>(
future: _calculation,
// a previously-obtained Future<String> or null
builder: (BuildContext context,
AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return new RefreshIndicator(
key: _refreshIndicatorKey,
color: Colors.blue,
onRefresh: () {
return _calculation = getCalculation(); // EDITED
},
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Text('Result: ${snapshot.data}')
)
);
break;
default:
return null;
}
},
)
Future<String> getCalculation() async {
try {
/*Write your API here or what ever u want to get when pull to refresh*/
return ""/*the value of api*/; //EDITED
} catch (e) {
///Handle Exception here. So in FutureBuilder we can capture it in snapshot.hasError
return Future.error(e.toString());
}
}
You have to access the snapshot, provided builder parm:
So, snapshot.data gives you the Future.
new FutureBuilder<String>(
future: _calculation, // a Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('Press button to start');
case ConnectionState.waiting: return new Text('Awaiting result...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Text('Result: ${snapshot.data}');
}
},
)
Example: https://flutter.io/cookbook/networking/background-parsing/
Doc: https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html
I'm trying to build a Save button that lets the user save/ unsave (like/ unlike) items displayed in a ListView.
What I have so far:
Repository that provides a Future<bool> that determines which state the icon should be rendered in
FutureBuilder that calls the repository and renders the icon as either saved/ unsaved.
Icon wrapped in a GestureDetector that makes a call to the repository within a setState call when onTap is invoked.
`
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _repository.isSaved(item),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
case ConnectionState.active:
return Icon(Icons.favorite_border);
case ConnectionState.done:
return GestureDetector(
child: Icon(
snapshot.data ? Icons.favorite : Icons.favorite_border,
color: snapshot.data ? Colors.red : null),
onTap: () {
setState(() {
if (snapshot.data) {
_repository.removeItem(item);
} else {
_repository.saveItem(item);
}
});
},
);
}
});
}
`
The issue I'm having is that when I tap to save an item in the list - the item is saved however the icon is not updated until I scroll it off screen then back on again.
When I tap to unsave an item, it's state is reflected immediately and updates as expected.
I suspect that the save call is taking longer to complete than the delete call. Both of these are async operations:
void removeItem(String item) async {
_databaseClient.deleteItem(item);
}
void saveItem(String item) async {
_databaseClient.saveItem(item);
}
#override
void deleteItem(String item) async {
var client = await db;
client.delete("items_table", where: "item = '$item'"); // returns Future<int> but I'm not using this currently
}
void _saveItem(String item) async {
var client = await db;
client.insert("items_table", item); // returns Future<int> but I'm not using this currently
}
Future<bool> isSaved(String name) async {
var matching = await _databaseClient.getNameByName(name);
return matching != null && matching.isNotEmpty;
}
Any idea what could be causing this?
When you tap the button, setState will be called. then FutureBuilder will wait for the isSaved method. if the save method is being in progress. isSaved will return the last state and Icon will not change.
I suggest to wait for the result of Save and Remove method and call setState after that.
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _repository.isSaved(item),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
case ConnectionState.active:
return Icon(Icons.favorite_border);
case ConnectionState.done:
return GestureDetector(
child: Icon(
snapshot.data ? Icons.favorite : Icons.favorite_border,
color: snapshot.data ? Colors.red : null),
onTap: () async{
if (snapshot.data) {
await _repository.removeItem(item);
} else {
await _repository.saveItem(item);
}
setState(() {
});
},
);
}
});
}
However, if the methods take so long, it delays which cause bad user experience. it better to change the icon to progress circle during running methods.