问题
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
- when widget state created initState() runs once before build() is first time called
- when build() done you have Button with onPressed callback configured
- user clicks that Button and function getUserData() is called
- because function is asyncronous we have result somewhere in future
- 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