Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Don't use BuildContext across sync gaps

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading