如何将从Firebase检索到的数据放入Flutter中的小部件? [英] How can I put retrieved data from firebase to a widget in Flutter?

查看:62
本文介绍了如何将从Firebase检索到的数据放入Flutter中的小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

因此,当我按下按钮时,此函数将打印以控制台从Firebase Firestore检索的数据.但是我想将它们放到小部件中并在我的应用程序中显示它们.例如:Text(printData())-但这是不允许的.我该怎么办?

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?

推荐答案

您需要使用 FutureBuilder 来显示异步获取的数据,因此请创建一个返回 Future的方法:

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

然后在 FutureBuilder 中将方法分配给属性 future :

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

这篇关于如何将从Firebase检索到的数据放入Flutter中的小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆