Flutter从Firestore检索文档数据

时间:2020-10-29 15:29:54

标签: flutter google-cloud-firestore

我正在尝试从当前uid的文档中检索数据“名称”和“电子邮件”。但是,我得到的数据是参考路径。有人可以指出我正确的方向吗?谢谢

Output in app Firestore DB Flutter codes

3 个答案:

答案 0 :(得分:0)

现在,您只是在引用文档路径。您需要查询该文档。

现在您拥有:

var userDetail = FirebaseFirestore.instance.collection('users').doc(user.uid);

将此更改为:

FirebaseFirestore.instance.collection('users').doc(user.uid)
    .get()
    .then((DocumentSnapshot userDetail) {
      if (userDetail.exists) {
        name = userDetail.data()['name'];
        email = userDetai.data()['email'];
      }
    });

参考:https://firebase.flutter.dev/docs/firestore/usage/#one-time-read

答案 1 :(得分:0)

CollectionReference users = FirebaseFirestore.instance.collection('users');

return FutureBuilder<DocumentSnapshot>(
  future: users.doc(USERID).get(),
  builder:
      (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

    if (snapshot.hasError) {
      return Text("Something went wrong");
    }

    if (snapshot.connectionState == ConnectionState.done) {
      Map<String, dynamic> data = snapshot.data.data();
      return Text("Full Name: ${data['name']} ${data['email']}");
    }

    return Text("loading");
  },
);

看看文档,您正在创建一个DocumentReference变量而不是DocumentSnapshot。 https://firebase.flutter.dev/docs/firestore/usage

答案 2 :(得分:0)

你好
您的代码中的错误是您没有在get()上使用方法DocumentReference[Firebase Docs Reference] 因此,下面是适合您的工作代码

DocumentSnapshot userDetail = await Firestore.instance.collection('users').doc(user.uid).get();
var name = userDetail.data()['name'];
var email = userDetail.data()['email'];

OR

var userDetail;
Firestore.instance.collection('users').doc(user.uid).get().then((DocumentSnapshot doc) {
   userDetail = doc;
   var name = userDetail.data()['name'];
   var email = userDetail.data()['email'];
});