I’m building a Flutter app, and in several places I have to call await
on some asynchronous functions before I can switch screens with Navigator.of(context).push
.
This doesn’t cause any functional issues when running the App, but I do have the warning in the code and I’d rather stick to the recommendation and do something about that warning.
Is there any recommended ways to get rid of that issue ?
Thanks in advance !
Short code example from within a button:
Button(
...
onTap: () async {
final canDisplay = await testCanDisplay();
if (canDisplay) {
final information = await fetchInformation();
if(information != null) {
Navigator.of(context).push(...);
} else {
showErrorMessage();
}
}
},
...),
2
Answers
The question is answered in docs here use_build_context_synchronously and also here on stack overflow do-not-use-buildcontexts-across-async-gaps
This warning is shown when context is being used in between async gap so to get rid of this issue use it like this