正在发生的事情的时间表在创建小部件状态时,initState()在第一次调用build()之前运行一次 build()完成后,您已配置了带有onPressed回调的Button 用户单击按钮并调用getUserData()函数因为函数是异步的,所以我们将来会在某处产生结果在结果上调用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 onwhen widget state created initState() runs once before build() is first time calledwhen build() done you have Button with onPressed callback configureduser clicks that Button and function getUserData() is calledbecause function is asyncronous we have result somewhere in futureon result setState() is called and userType fullfilled with some dataAnd if no errors occured now you have userType != nullPS if you describe desired behavior - add commments, we'll try to reach result you want 这篇关于为什么在flutter中无法到达initState内的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-18 18:08