How to get user id from Firebase Auth in Flutter?

烈酒焚心 提交于 2019-12-07 02:15:36

问题


I want to save user-related data in Firestore by assigning user id to a document as a field.

How to get user id from Firebase Auth?

Or is there a better way to store user data in Firestore?

I couldn't get user id from Firebase Auth in this way (the Text(_userId) returns _userId == null error):

String _userId;
  ...

  @override
  Widget build(BuildContext context) {
    FirebaseAuth.instance.currentUser().then((user) {
      _userId = user.uid;
    });

    return new Scaffold(
      appBar: new AppBar(
        title: new Text("App bar"),
      ),
      body: new Text(_userId),
    );
  }

回答1:


_userId is null because the widgets are being built before the Future returned by FirebaseAuth.instance.currentUser() has completed. Once it does complete it's too late and the widgets don't update. One way to work with it would be to use a FutureBuilder somewhat like this:

Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("App bar"),
    ),
    body: FutureBuilder(
      future: FirebaseAuth.instance.currentUser(),
      builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.hasData) {
          return Text(snapshot.data.uid);
        }
        else {
          return Text('Loading...');
        }
      },
    ),
  );
}


来源:https://stackoverflow.com/questions/49827598/how-to-get-user-id-from-firebase-auth-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!