为什么在flutter中无法到达initState内的变量? [英] Why can't I reach the variable inside an initState in flutter?

查看:58
本文介绍了为什么在flutter中无法到达initState内的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用通过使用void函数从Firestore中获取的变量,当我在相同的函数或其他函数中打印它时,它会获取它,但是当我在initState中使用它时,它会给出null的帮助!我想要的var是userType.代码 :getuserData表单firebase:

  void getUserData()异步{尝试 {firestoreInstance.collection('用户').document(usernameController.text).得到().then((value){setState((){电子邮件=(value.data)['电子邮件'];密码=(value.data)['密码'];性别=(value.data)['性别'];用户名=(value.data)['用户名'];userType =(value.data)['userType'];});});}抓住(e){print(e.toString);}} 

和初始化状态:

  void initState(){super.initState();FirebaseAuth.instance.currentUser().then((结果) {if(结果!= null){打印(用户类型);打印(结果);如果(userType =='Admin'){Navigator.pushReplacementNamed(context,'/AdminPage');}如果(userType =='学生'){Navigator.pushReplacementNamed(context,'/StudentPage');}如果(userType =='教师'){Navigator.pushReplacementNamed(context,'/TeacherPage');}} 别的 {showDialog(上下文:上下文,生成器:(BuildContext上下文){返回AlertDialog(标题:Text('Error'),内容:文字(请确保您可以连接互联网"),动作:[FlatButton(子代:文字("Ok"),onPressed:(){Navigator.of(context).pop();},)],);},);}},);} 

调用getuserdata:

  child:Center(子代:集装箱(宽度:250,高度:50,子代:FlatButton(onPressed:()=>{getUserData(),login()},子代:文字(登录",样式:TextStyle(颜色:Colors.deepOrangeAccent,fontSize:20,fontWeight:FontWeight.bold),),形状:RoundedRectangleBorder(borderRadius:BorderRadius.circular(25.0),),),),), 

解决方案

让我们找出为什么在 initState()中使用 userType == null 的原因...

正在发生的事情的时间表

  1. 在创建小部件状态时,initState()在第一次调用build()之前运行一次
  2. build()完成后,您已配置了带有onPressed回调的Button
  3. 用户单击按钮并调用getUserData()函数
  4. 因为函数是异步的,所以我们将来会在某处产生结果
  5. 在结果上调用setState()并用一些数据填充userType

如果现在没有发生错误,则您的用户类型为!= null

如果您描述了期望的行为,请注意-添加评论,我们将尽力达到您想要的结果

I am trying to use a variable that I got from firestore by using a void finction and when I print it in the same function or another function it gets it but when I use it in an initState it gives me null HELP! the var I want is userType. code : getuserData form firebase:

void getUserData() async {
    try {
      firestoreInstance
          .collection('Users')
          .document(usernameController.text)
          .get()
          .then((value) {
        setState(() {
          email = (value.data)['email'];
          password = (value.data)['password'];
          gender = (value.data)['gender'];
          username = (value.data)['username'];
          userType = (value.data)['userType'];
        });
      });
    } catch (e) {
      print(e.toString);
    }
  }

and the initstate :

void initState() {
    super.initState();
    FirebaseAuth.instance.currentUser().then(
      (result) {
        if (result != null) {
          print(userType);
          print(result);
          if (userType == 'Admin') {
            Navigator.pushReplacementNamed(context, '/AdminPage');
          }
          if (userType == 'Student') {
            Navigator.pushReplacementNamed(context, '/StudentPage');
          }
          if (userType == 'Teacher') {
            Navigator.pushReplacementNamed(context, '/TeacherPage');
          }
        } else {
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('Error'),
                content: Text(
                    'Please make sure that you have an internet connection'),
                actions: [
                  FlatButton(
                    child: Text("Ok"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  )
                ],
              );
            },
          );
        }
      },
    );
  }

calling getuserdata:

child: Center(
                      child: Container(
                        width: 250,
                        height: 50,
                        child: FlatButton(
                          onPressed: () => {getUserData(), login()},
                          child: Text(
                            "Login",
                            style: TextStyle(
                                color: Colors.deepOrangeAccent,
                                fontSize: 20,
                                fontWeight: FontWeight.bold),
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25.0),
                          ),
                        ),
                      ),
                    ),

解决方案

Let's find out why you have userType == null in initState()...

Timeline of what is going on

  1. when widget state created initState() runs once before build() is first time called
  2. when build() done you have Button with onPressed callback configured
  3. user clicks that Button and function getUserData() is called
  4. because function is asyncronous we have result somewhere in future
  5. on result setState() is called and userType fullfilled with some data

And if no errors occured now you have userType != null

PS if you describe desired behavior - add commments, we'll try to reach result you want

这篇关于为什么在flutter中无法到达initState内的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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