简体   繁体   中英

Flutter Firebase get current user data

I am trying to build a profile page where it will capture user log in credentials and upon successful log in, there will be a profile page that will display user info.

CODE

  firebase_auth: ^0.14.0+5
  cloud_firestore: ^0.11.0+2
  provider: ^3.1.0

This are the dependencies version I am using.

 void createRecord(name, email, password) async {
  await databaseReference.collection("users").add({
      'name' : name,
      'email': email,
      'password': password,
  });
}

createRecord will be called when user registers successfully.

void getData() {
     databaseReference
        .collection("users")
        .getDocuments()
        .then((QuerySnapshot snapshot) {
          snapshot.documents.forEach((f) => print("${f.data}"));
     });
  }

Right now I can only print ALL data instead of current logged in user data. (only need name and email)

Next question

How do I get the data to show on my UI?

what you are doing wrong is fetching all the users instead of one single user.

String userid

 void createRecord(name, email, password) async {
 final result =  await databaseReference.collection("users").add({
      'name' : name,
      'email': email,
      'password': password,
  });

userid = result;
}

assign the result of the query to a variable, this will contain all the data. You can use this instead of making another call to show the user data. But if you still want to make another call.

Future<User> getData() async {
    final user =  await databaseReference
        .collection("users")
        .doc(userid);
   
return user;  
  }

Although would not recommend making two calls for this. But it should work.

Regarding your second question, since you're using provider , you can use a Channotifier and a ChangeNotifierProvider to insert user data into state and use it in UI.

  • Create a User model
  • Create a
Profile with ChangeNotifier {
User _user;
User get user => _user;

//call get data here

getProfile()async{

_user = await getdata();

notifylistneres();
}

  • Then use it in your UI using Provider.of<Profile>(context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM