0

I need help with my flutter code which involves firebasefirestore. This is my code. I'd like to retrieve from the database the image_url from the map.

    final userData = FirebaseFirestore.instance
    .collection('users')
    .doc(FirebaseAuth.instance.currentUser.uid)
    .get();

But in userData is not a map exactly. It is a Future<DocumentSnapshot<Map<String, dynamic>>>. This is what get returns . My question is, how do I scope into the Map<String, dynamic> ? I mean to get the userData['image_url']... ? Because I get this error: The operator '[]' isn't defined for the type 'Future<DocumentSnapshot<Map<String, dynamic>>>'. Thanks alot!

Yarin0600
  • 1
  • 1
  • 4
  • 1
    if it is a future function you need to add await keyword in front of it. Here; final userData = await FirebaseFirestore... .Then you can reach the value – Timur Turbil Jul 09 '22 at 11:59

1 Answers1

1

As shown in the Firebase documentation on getting a document, that'd be:

final docRef = db.collection("users").doc(FirebaseAuth.instance.currentUser.uid);
docRef.get().then(
  (DocumentSnapshot doc) {
    final data = doc.data() as Map<String, dynamic>;
    // ...
  },
  onError: (e) => print("Error getting document: $e"),
);

You can also use await as Timur commented, in which case it'd be:

final docRef = db.collection("users").doc(FirebaseAuth.instance.currentUser.uid);
DocumentSnapshot doc = await docRef.get();
final data = doc.data() as Map<String, dynamic>;
// ...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807