Can anyone help me understand this piece of code:
String? userName = "";
String? userEmail = "";
AuthService authService = AuthService();
@override
void initState() {
// TODO: implement initState
super.initState();
gettingUserData();
}
while defining gettingUserData(), using async, await needs hotreload to show the email
gettingUserData() async {
setState(() async {
userName = await HelperFunction.getUsername();
userEmail = await HelperFunction.getUseremail();
});
}
But defining it using .then doesn't need hot relaod
gettingUserData() {
HelperFunction.getUseremail().then((value) {
setState(() {
userEmail = value;
});
});
HelperFunction.getUsername().then((value) {
setState(() {
userName = value;
});
});
}
Can anyone help me understand why this is?
CodePudding user response:
The two versions are not equivalent. The Future.then
version calls setState
after each Future
completes.
The await
version calls setState
with an asynchronous callback, which setState
does not expect. Since setState
expects a VoidCallback
argument, it expects its callback to complete synchronously, and it will not be await
ed. setState
therefore executes and returns immediately before waiting for either of the Future
s complete.
One way to correct your await
version is to await
the Future
s first and to then call setState
:
Future<void> gettingUserData() async {
var userName = await HelperFunction.getUsername();
var userEmail = await HelperFunction.getUseremail();
setState(() {
this.userName = userName;
this.userEmail = userEmail;
});
}