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, even if I check for context.mounted

I am using flutter 3.22.3 and Dart 3.4.4 and my editor still warns me about context … even if I check if the context is mounted.

I have this helper function showToastMessage and the async gaps:

void showToastMessage(BuildContext context, String message) {
    ScaffoldMessenger.of(context).clearSnackBars();
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message))
    );
}

// somewere in the code an async func

void _submit async {
    ...
    var result = await CallAPi().postData(data, '/login');
    
    ...
    
    // check the context !!!
    if (context.mounted) {
        showToastMessage(context, result.message); // it still complains about the context "Don`t use BuildContext across async gaps ...."
    }
}

I am checking like in the documentation for the context…. so why I am still get the warning ????

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

What am I missing ?

>Solution :

Now in newer version of flutter you can use mounted directly inside StatefulWidget

instead of using

if (context.mounted) {
  pop(context);
}

Use

if (mounted) {
  pop(context);
}

you can check the details when to use context.mounted and mounted here: use_build_context_synchronously

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