【问题标题】:Flutter Firebase Auth returns null, then returns the correct valueFlutter Firebase Auth 返回 null,然后返回正确的值
【发布时间】:2019-08-05 09:48:18
【问题描述】:

我在使用当前用户的 ID (UID) 时遇到问题。以下代码“有效”,但在某些情况下,_currentUID 在输出正确值之前首先输出“null”。

class _ContactsScreenState extends State<ContactsScreen> {

 String _currentUID;

 @override
 initState() {
   super.initState();
   loadCurrentUser();
 }

 loadCurrentUser() async {
   var currentUID = await _getCurrentUID();
   setState(() {
     this._currentUID = currentUID;
   });
 }

 Future<String> _getCurrentUID() async {
   FirebaseUser user = await FirebaseAuth.instance.currentUser();
   return user.uid;
 }

 @override
 Widget build(BuildContext context) {

   if (_currentUID == null){
     print("current UserID = null");
   } else {
     print("current UserID = $_currentUID");
   }

   return StreamBuilder(
      ...

所以这实际上工作正常,按预期输出结果,但是经过检查,打印输出如下:

flutter: current UserID = null // why is it printing null?
flutter: current UserID = abcd1234abcd //correct

不寻常的是,这只会在用户第二次访问屏幕时发生。第一次加载屏幕/页面时,它将正确输出“仅”实际的当前用户 ID。当用户返回同一页面时,它将打印当前用户两次(如上所示)。

【问题讨论】:

  • 我认为当 auth 对象尚未完成初始化时会发生这种情况。为避免这种情况,您可以使用AuthStateListener。
  • 请确保在身份验证操作完成之前不要导航到屏幕。 currentUser() 函数也不是异步的。

标签: firebase dart flutter firebase-authentication


【解决方案1】:

这是完全正常的。

loadCurrentUser 是异步的,所以如果_ContactsScreenState 被创建,实例将在一段时间后完成。只有这样才能分配_currentUID。

如果框架在分配之前调用build,那么它将为空。让build 简单地返回Container 或进度指示器(如果它为空)是正常的。一旦分配,build 将再次被调用。这次它不会为空,您可以构建“正常”屏幕。

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 2021-09-28
    • 2022-01-16
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多