Flutter误差:无法访问从Firebase Firestore获取的快照内的数据

4urapxun  于 2022-12-19  发布在  Flutter
关注(0)|答案(2)|浏览(163)

在Flutter 3.3.9中,我使用Streambuilder从Firestore数据库中获取一条记录,我使用以下代码段来完成此操作:

StreamBuilder<Object>(
                stream: FirebaseFirestore.instance
                    .collection('users')
                    .doc(userId)
                    .snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Text('Loading...');
                  }
                  return Text(
                    snapshot.data!.doc['username'], // This line is marked as error bexcause "doc" is illegal.
                    ),
                  );
                },
              ),

snapshot.data!.doc['username']给出以下错误:
没有为类型"Object"定义getter "doc"。
I verified that the 'Object' is of type "AsyncSnapshot" (=snapshot.runtimeType). It looks like the only getters available for the snapshot.data are hashCode, runtimeType, toString(), and noSuchMethod(..).
我试过了

snapshot.data!().doc['username'],

但这也不管用,错误是"表达式没有求值为函数,所以不能调用"
我可以在不使用StreamBuilder的情况下访问数据。

final docRef = FirebaseFirestore.instance
                      .collection('users')
                      .doc(userId);

                  docRef.get().then(
                    (DocumentSnapshot doc) {
                      final data = doc.data() as Map<String, dynamic>;
                      print(data['username']);
                    },
                    onError: (e) => print("Error getting document: $e"),
                  );
kupeojn6

kupeojn61#

你有两个错误,在你的代码中,你应该指定AsyncSnapshot的类型,如下所示:

StreamBuilder<DocumentSnapshot>( // Specified type
                stream: FirebaseFirestore.instance
                    .collection('users')
                    .doc(userId)
                    .snapshots(),
                builder: (context, AsyncSnapshot<DocumentSnapshot>  snapshot) { //Specified type
    //...

现在使用snapshot.data!,它应该是DocumentSnapshot类型,正如我所看到的,您试图获取该文档的数据,因此您还需要更改以下行:

snapshot.data!.doc['username'],

改为:

(snapshot.data!.data() as Map<String, dynamic>)['username'],

现在它将正确地访问用户名字段。

11dmarpk

11dmarpk2#

您以错误的方式定义了StreamBuilder的类型,请将其更改为:

StreamBuilder<AsyncSnapshot>(

   ... 
)

相关问题