How can I put retrieved data from firebase to a widget in Flutter?

旧街凉风 提交于 2021-01-29 13:56:12

问题


  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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!