skip to Main Content

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


  1. The question is answered in docs here use_build_context_synchronously and also here on stack overflow do-not-use-buildcontexts-across-async-gaps

    Login or Signup to reply.
  2. This warning is shown when context is being used in between async gap so to get rid of this issue use it like this

     Button(...
         onTap: () async {
            await testCanDisplay().then((canDisplay) async {
              if (canDisplay) {
                await fetchInformation().then((information) {
                  if (information != null) {
                    Navigator.of(context).push(...);
                      } else {
                        showErrorMessage();
                        }
                      });
                      }
                  });
                },
            ...),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search