Flutter Firebase“无效成员,null:'数据'”

时间:2020-10-11 17:35:43

标签: firebase flutter dart google-cloud-firestore

因此,我想遍历文档中的所有字段并在列表视图中显示它们。我尝试了这个,但是出现了这个错误:

The following JSNoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot>(dirty, state: _FutureBuilderState<DocumentSnapshot>#ccb6a):
NoSuchMethodError: invalid member on null: 'data'

这是我的代码。该文档有数据,但是我可以想象数据为空,因为它没有加载?:

return FutureBuilder<DocumentSnapshot>(
        future: FirebaseFirestore.instance
            .collection("Collection")
            .doc(currentCategory)
            .get(),
        builder:
            (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          print(snapshot.data.data());
          return Container(
            child: Text(""),
          );
        });
  }

编辑:在这里有效:

void loadEvents() {
    if (currentCategory != "") {
      FirebaseFirestore.instance
          .collection("Category")
          .doc(currentCategory)
          .get()
          .then((value) => {
                events.clear(),
                value.data().forEach((key, value) {
                  setState(() {
                  });
                }),
              });
    }
  }

1 个答案:

答案 0 :(得分:0)

尝试一下:

    return FutureBuilder<DocumentSnapshot>(
        future: FirebaseFirestore.instance
            .collection("Collection")
            .doc(currentCategory)
            .get(),
        builder:
            (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          // ***check if the future has received data before attempting to process***
          if (snapshot.hasData) {
            print(snapshot.data.data());
            // <add additional processing here>
          }
          return Container(
            child: Text(""),
          );
        });