无法使用 cloud firestore 获取文档或文档:^2.1.0 flutter

Cannot get documents or docs with cloud firestore : ^2.1.0 flutter

我刚刚升级到 cloud firestore: ^2.1.0,我在 snapshots.data?.documentssnapshots.data?.docs 上遇到错误消息 The getter 'documents' 没有为上述代码中的类型 'Object'. 定义:

@override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseFirestore.instance.collection('Courses').snapshots(),
      builder: (context1, snapshot) {
        //just add this line
        if (snapshot.data == null) return CircularProgressIndicator();
        return ListView.builder(
          itemCount: snapshot.data?.documents.length,
          itemBuilder: (context2, index) {
            return GestureDetector(
              onTap: () => Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => DetailCourseScreen(
                      snapshot.data?.documents[index]['title'],
                      snapshot.data?.documents[index]['storage'],
                      index),
                ),
              ),
              child: _buildCourseList(
                  context2, snapshot.data?.documents[index], index),
            );
          },
        );
      },
    );
  }

这是我的 pubspec.yaml :

environment:
  sdk: '>=2.12.0 <3.0.0'

dependencies:

  cloud_firestore: ^2.1.0
  firebase_core: ^1.1.1
  firebase_storage: ^8.0.6
  firebase_image: ^1.0.1

我理解你的困惑。自 cloud_firestore 2.0.0 更新以来,访问 Cloud Firestore 的数据变得有点奇怪。您可以使用以下代码访问您的数据:

StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance
          .collection('Courses')
          .withConverter<Map<String, dynamic>>(
            fromFirestore: (snapshot, _) => snapshot.data() ?? Map<String, dynamic>(),
            toFirestore: (model, _) => Map<String, dynamic>.from(model as Map),
          )
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.data == null) return CircularProgressIndicator();
        return ListView.builder(
          itemCount: snapshot.data?.docs.length,
          itemBuilder: (context2, index) {
            return GestureDetector(
              onTap: () => Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => DetailCourseScreen(
                      snapshot.data?.docs[index].data()['title'],
                      snapshot.data?.docs[index].data()['storage'],
                      index),
                ),
              ),
              child: _buildCourseList(context2, snapshot.data?.docs[index].data(), index),
            );
          },
        );
      },
    );

您可以在此处阅读有关此更新的更多信息:https://pub.dev/packages/cloud_firestore/changelog#200