Home > Software engineering >  Getting current user's data from firebase firestore in flutter
Getting current user's data from firebase firestore in flutter

Time:01-18

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']

CodePudding user response:

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);
 });

CodePudding user response:

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 //            
  •  Tags:  
  • Related