Home > Software engineering >  How to retrieve current user data from firebase?
How to retrieve current user data from firebase?

Time:06-04

I tried this way, but i'm getting an error.

The error:

The method 'data' isn't defined for the type 'CollectionReference'. (undefined_method at [myapp] android\app\lib\useracc.dart:32)

void getData() async{
    User? user = await FirebaseAuth.instance.currentUser;
        var vari =FirebaseFirestore.instance.collection("users");

        setState (() {
          name = vari.data()['firstname'];
        }
        );

  }

Signup/Register Page

Future<User?> _register(String fname,String lname ,String email, String password) async{
    FirebaseAuth _auth = FirebaseAuth.instance;

    FirebaseFirestore _firestore = FirebaseFirestore.instance;
    try {
      UserCredential userCrendetial =  await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text);

      print("Account created Succesfull");

      userCrendetial.user!.updateDisplayName(fname);
      userCrendetial.user!.updateDisplayName(lname);

      await _firestore.collection('users').doc(_auth.currentUser!.uid).set({
        "firstname": fname,
        "lastname" : lname,
        "email": email,
        "uid": _auth.currentUser!.uid,
      });

      return userCrendetial.user;
    } catch (e) {
      print(e);
      return null;
    }
  }

This is the user account from where i want to fetch info:

Please help. I'm struck here a long time.

CodePudding user response:

You should retrieve the currentUser document then access its data:

void getData() async{
    var vari = await FirebaseFirestore.instance
            .collection("users")
            .doc(FirebaseAuth.instance.currentUser.uid)
            .get();

    setState (() {
      name = vari.data()['firstname'];
    });
}

CodePudding user response:

if you've saved your user's details in firestore and its document id is the same as that of user ID (which is preferred for ease of access and control), then:

var vari =FirebaseFirestore.instance.collection("users").doc(user!.UserId).get();

This gets the document of the user, and the type is DocumentSnapshot.

Map<String,dynamic> userData = vari as Map<String,dynamic>;

now userData is stored in form of Map. suppose you want to access their 'name', so the syntax now goes like userData['name'].

Similarly other fields can be accessed from variable. It's preferred to store userData in a Provider to access it's contents anywhere in your app.

Heres a sample database structure

Full code snippet

void getData() async{
    User? user = await FirebaseAuth.instance.currentUser;
        var vari =FirebaseFirestore.instance.collection("users").doc(user!.UserId).get();
Map<String,dynamic> userData = vari as Map<String,dynamic>;

        setState (() {
          name = userData['firstname']; //or name = userData['name']
        }
        );

  }
  • Related