简体   繁体   English

如何从Firebase身份验证获取用户ID作为字符串?

[英]How to get user id from firebase auth as string?

I'm trying to insert data to firestore with the authenticated user id as the document id but i got null from the parameter. 我正在尝试使用经过身份验证的用户ID作为文档ID将数据插入到Firestore中,但是我从参数中得到了null。

Please take a look at my script. 请看一下我的脚本。

void didChangeDependencies() {
  uid = '';
  super.didChangeDependencies();
}

Future _fetchUID() async {
  var auth = AuthProvider.of(context).auth;
  return await auth.getCurrentUser().then((user) => _uid = user.uid);
}

_validateAndSubmit() async {
  setState(() {
    _errorMessage = '';
    _isLoading = true;
  });

  if (_validateAndSave()) {
    try {
      _fetchUID();
      await Report.create(_uid, _suspectName, _plateNumber, _civilizationId,
          _drivingLicenseId, _clause, _description);
      return Navigator.of(context).pop();
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = e.message;
      });
      print(_errorMessage);
      throw Exception(e);
    }
  }
}

In this method below you can see that I have already tried to set the _uid , but I still cannot get the _uid value. 在下面的此方法中,您可以看到我已经尝试设置_uid ,但是仍然无法获得_uid值。

Future _fetchUID() async {
  var auth = AuthProvider.of(context).auth;
  return await auth.getCurrentUser().then((user) => _uid = user.uid);
}

This is how the getCurrentUser() method looks like. 这就是getCurrentUser()方法的样子。

Future<FirebaseUser> getCurrentUser() async {
  FirebaseUser user = await _firebaseAuth.currentUser();
  return user;
}

Am I doing it wrong? 我做错了吗?

First of all, you mixed the Future.then syntax and the async await syntax. 首先,将Future.then语法和async await语法混合在一起。
You should probably write your method this way: 您可能应该这样写方法:

void _fetchUID() async {
  var auth = AuthProvider.of(context).auth;
  _uid = (await auth.getCurrentUser()).uid;
}

If _uid is still null for you after calling _fetchUID this way, then you are simply not signed in, meaning that there is no FirebaseUser as you first need to sign in. 如果_uid仍然是null打完电话后对您_fetchUID这种方式,那么你根本就没有签署,这意味着没有FirebaseUser ,你首先需要登录。

In your _validateAndSubmit method, you also first need to await your _fetchUID call, otherwise it will pass _uid before it has been assigned a value. _validateAndSubmit方法中,您还首先需要等待 _fetchUID调用,否则它将在分配值之前通过_uid

...
try {
  await _fetchUID();
  await Report.create(_uid, ..);
  ...

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

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