0

I'm having some trouble getting printing out a string in a firestore document, and it's only returning null. Anything that might be going wrong?

String getDoc(String group, String channel, String message)
{
  var data;
  final docRef = db.collection('Groups').doc('$group').collection('Channel').doc('$channel').collection('Messages').doc('$message');
  docRef.get().then(
      (DocumentSnapshot doc) {
        data = doc.data() as Map<String, dynamic>;
      },
      onError: (e) => print("Error getting document: $e"),
  );
  print(data);
  var returnMessage = data?['messageBody'];

  print(returnMessage);
  return returnMessage;
}

this is the current message. ======== Exception caught by gesture =============================================================== The following TypeErrorImpl was thrown while handling a gesture: Expected a value of type 'String', but got one of type 'Null'

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Getting data from Firestore (and pretty much any modern cloud API) is an asynchronous operation. If you add some more logging (or run in a debugger), you'll see that your `return returnMessage;` runs *before* the `data = doc.data() as Map;` every runs. You can't return something now, that hasn't loaded yet. Some sources where you can learn more: https://dart.dev/codelabs/async-await, https://www.youtube.com/watch?v=SmTCmDMi4BY and the dupes I linked – Frank van Puffelen Mar 31 '23 at 21:47
  • just use `async/await` instead of `then`. You got null because you initialized the variable, printed it out, and later (async) it populated. Or use print inside `then` block – RAI Mar 31 '23 at 21:51

0 Answers0