简体   繁体   English

Flutter Firebase 获取当前用户数据

[英]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.用户注册成功后会调用createRecord。

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?如何让数据显示在我的 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.关于您的第二个问题,由于您使用的是provider ,因此您可以使用ChannotifierChangeNotifierProvider将用户数据插入状态并在 UI 中使用它。

  • Create a User model创建User模型
  • 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)然后使用Provider.of<Profile>(context)在您的 UI 中使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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