问题
final String uid;
final firestoreInstance = Firestore.instance;
void printData() async{
var firebaseUser = await FirebaseAuth.instance.currentUser();
firestoreInstance.collection("users").document(firebaseUser.uid).get().then((value){
print(value.data);
});
}
So this function prints to console the retrieved data from firebase firestore when I press the button. But I want to put them into a widget and display them in my app. For ex: Text(printData()) - but it's not allowed. How can I do that?
回答1:
You need to use a FutureBuilder
to display data that you are getting asynchronously, therefore create a method that returns a Future
:
Future<DocumentSnapshot> getDocument() async{
var firebaseUser = await FirebaseAuth.instance.currentUser();
return Firestore.instance.collection("users").document(firebaseUser.uid).get();
}
Then in the FutureBuilder
assign the method to the property future
:
body: Container(
padding: EdgeInsets.all(10.0),
child: FutureBuilder(
future: getDocument(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Text(snapshot.data["name"].toString());
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
),
Assuming you have the following db:
Collection ("users") ----> Document (userId) ---> fields name : your_name
Read more about future:
https://api.dart.dev/stable/2.9.1/dart-async/Future-class.html
https://dart.dev/codelabs/async-await
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
来源:https://stackoverflow.com/questions/63448903/how-can-i-put-retrieved-data-from-firebase-to-a-widget-in-flutter