Why can't I reach the variable inside an initState in flutter?

只谈情不闲聊 提交于 2021-02-11 13:37:27

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/62691949/why-cant-i-reach-the-variable-inside-an-initstate-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!