如何从 Flutter 中的 Firebase Auth 获取用户 ID? [英] How to get user id from Firebase Auth in Flutter?

查看:27
本文介绍了如何从 Flutter 中的 Firebase Auth 获取用户 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将用户 ID 作为字段分配给文档来将与用户相关的数据保存在 Firestore 中.

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

如何从 Firebase Auth 获取用户 ID?

或者是否有更好的方法在 Firestore 中存储用户数据?

我无法以这种方式从 Firebase Auth 获取用户 ID(Text(_userId) 返回 _userId == null 错误):

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

推荐答案

_userId 为 null 因为在 FirebaseAuth.instance.currentUser() 返回的 Future 之前构建小部件代码> 已完成.一旦完成,为时已晚,小部件不会更新.使用它的一种方法是使用 FutureBuilder 有点像这样:

_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...');
        }
      },
    ),
  );
}

这篇关于如何从 Flutter 中的 Firebase Auth 获取用户 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆