Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

flutter - Getting a document from Firestore results in "The method 'data' was called on null. Receiver: null Tried calling: data())"

I am new to Flutter and trying to get a document from a collection; there is no error in the code but, still, the document is not obtained.

I am trying to return a variable having String in the method _onPressed() but I'm stuck at that point.

 Future _onPressed() async{
    var msg;
    await db.collection('Messages').doc(widget.brew.id).get().then((value){
      print(value.data()['Message']);
      return value.data()['Message'];
    });
    msg =  msg.data()['Message'];
    return msg;
  }
question from:https://stackoverflow.com/questions/65832188/getting-a-document-from-firestore-results-in-the-method-data-was-called-on-nu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Wrong assignment done here. change the above code

Future _onPressed() async{
    var docSnap = await db.collection('Messages').doc(widget.brew.id).get();
    if (docSnap.exists) {
        print('Document data: ${documentSnapshot.data()}');
        return docSnap.data()['Message'];
    } else {
        print('Document does not exist on the database');
        return docSnap.data()['Message'];
    }

  }

In current snippet, msg.data() throws the err as the msg was null at that time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...