I have a button in my Flutter app.
onPressed: () async {
try {
final newUser = await _auth.createUserWithEmailAndPassword(email: email, password: password);
if (newUser.user != null) {
await Future.delayed(Duration.zero);
Navigator.of(context).pushNamed(ChatScreen.id);
}
} catch (e) {
print(e);
}
},
The IDE reports "Don’t use BuildContext across sync gaps.".
What am I doing wrong ?
>Solution :
When doing asynchronous tasks during widget’s synchronous operations, you must check the widget is still available.
For your case, right before the Navigator line, add this line
if (!mounted) return;
By doing so you check the current Widget is mounted and usable. If the Widget is being rebuilt or destroyed, checking if it’s mounted will return false.
If it returns true it means the Widget is ready and you can use async / sync tasks almost everywhere.