0

I want to get data from firestore, but I can't seem to do it properly and it always returns null. Here's what I tried:

Map<String, dynamic>? userMap2;

void getCurrentUser() async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;

final User? user = _auth.currentUser;
final uuid = user!.uid;

setState(() {
  isLoading = true;
});

await _firestore
    .collection('users')
    .where("uid", isEqualTo: uuid)
    .get()
    .then((value) {
  setState(() {
    userMap2 = value.docs[0].data();
    isLoading = false;
  });
  print(userMap2);
});

}

and when I try to use that data, I try to use it like this: userMap2!['firstName']

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

0

Try to put user data in document and then use,

     _firestore
     .collection('users')
     .doc(uuid)
     .get().then((value) {
      setState(() {
      userMap2 = value.docs[0].data();
      isLoading = false;
  });
   print(userMap2);
 });
Coder Addy
  • 423
  • 3
  • 18
  • It gave me an error like this: "error: The getter 'docs' isn't defined for the type 'DocumentSnapshot>'. (undefined_getter at [sportal] lib\screens\messageSearch_s.dart:71)" – Burcu Sultan Orhan Jan 17 '22 at 11:29
0

In React, calling setState is an asynchronous operation. In addition, loading data from Firestore is an asynchronous operation. This means that in your current code, the print(userMap2) runs before your then callback is called, and even further before the userMap2 = value.docs[0].data() has been completed.

I recommend not combining then with await, and doing:

const value = await _firestore // 
    .collection('users')
    .where("uid", isEqualTo: uuid)
    .get();
setState(() {
  userMap2 = value.docs[0].data();
  isLoading = false;
});
print(value.docs[0].data()); // 

On the first line I marked, we're now taking the return value from the awaited get(), so that we no longer need a then block. This handles the asynchronous nature of the call to Firestore.

Then on the second marked line, we print the value directly from the results from the database, instead of from the setState call. This addresses the asynchronous nature of calling setState.

For more on these, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807