LateInitializationError:字段' _userData @ 32329253'尚未初始化 [英] LateInitializationError: Field '_userData@32329253' has not been initialized

查看:108
本文介绍了LateInitializationError:字段' _userData @ 32329253'尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试初始化数据时获取此信息.

Getting this when trying to initialize data.

在构建UserProfile(脏,状态:_UserProfileState#752a9)时引发了以下LateError:LateInitializationError:字段'_userData @ 32329253'尚未初始化."

The following LateError was thrown building UserProfile(dirty, state: _UserProfileState#752a9): LateInitializationError: Field '_userData@32329253' has not been initialized."

代码如下:

    late final User _user;
    late final DocumentSnapshot _userData;
    
      @override
      void initState() {  
        super.initState();
        _initUser();
      }
    
      void _initUser() async {
        _user = FirebaseAuth.instance.currentUser!;
        try {
          _userData = await FirebaseFirestore.instance
              .collection('users')
              .doc(_user.uid)
              .get();
        } catch (e) {
          print("something went wrong");
        }
      }

构建功能甚至没有运行,因为我尝试打印_user和_userData来检查它们是否已初始化.
如果我尝试在initUser()函数中打印_user和_userData,则在错误语句后将打印_user和_userData.
请帮助我找到解决此错误的方法.

The build function is not even running as i tried to print _user and _userData to check if they have been initialized.
If i try to print _user and _userData in initUser() function, _user gets printed and _userData gets printed after the error statements.
Please help me find a way out through this error.

推荐答案

即使您在 initUser()中初始化这些变量,但如果在其中使用变量,也会出现此错误 build()方法,因为 initUser()是异步的,这意味着从集合中获取数据将花费一些时间.要解决此问题,您可以执行以下操作:

Even though you are initializing these variables inside the initUser(), but you will get this error if you are using the variables inside the build() method since initUser() is asynchronous meaning it will take time to get the data from the collection. To solve this you can do:

@override
      void initState() {  
        super.initState();
        _initUser().whenComplete((){
          setState(() {});
       });
      }

这将使用新值重建小部件树.

This will rebuild the widget tree with the new values.

这篇关于LateInitializationError:字段' _userData @ 32329253'尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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