简体   繁体   中英

Flutter firestore QuerySnapshot has no instance of getter 'documents' in Android

I am trying to retrieve the values of the variables from the firestore cloud. Through implementing the code, I've seemed to come across an error, and I've spent hours getting frustrated over this, trying to find solutions here and elsewhere. The error I've faced alongside the code is as per below.

The following NoSuchMethodError was thrown building StreamBuilder(dirty, state:_StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot>#4939b): Class 'QuerySnapshot' has no instance getter 'documents'. Receiver: Instance of 'QuerySnapshot' Tried calling: documents

Error Displayed on the Virtual Device

Code that I am using:

 Widget buildStreamBuilder() {
     return Container(
        child: !_success
            ? Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
          ),
        )
            : StreamBuilder(
          stream: FirebaseFirestore.instance.collection('sensors').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
                ),
              );
            } else {
              snapshot.data.documents.forEach((doc) {
                if (doc.documentID == 'cSBKpiEe1XKmQC8BDzMk') {
                  print('current value = ${doc['BatStat']}'); //var1
                  globalCurrentSensorValue = doc['BatStat'].toDouble();
                }
              });
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: Container(),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(),
                    )
                  ],
                ),
              );
            }
          },
        ));
  }

Change this:

snapshot.data.documents.forEach((doc)

into this:

snapshot.data.docs.forEach((doc)

QuerySnapshot class contains a property called docs which will return all the documents in a collection.

if I am not wrong you are accessing the document data incorrectly. try this:

 if (doc.documentID == 'cSBKpiEe1XKmQC8BDzMk') {
              //use doc.data()[' '] method
              print('current value = ${doc.data()['BatStat']}'); //var1
              globalCurrentSensorValue = doc.data()['BatStat'].toDouble();
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM