0

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();
    }
  }
},
...),
Tom
  • 163
  • 1
  • 11
  • 1
    Does this answer your question? [Do not use BuildContexts across async gaps](https://stackoverflow.com/questions/68871880/do-not-use-buildcontexts-across-async-gaps) – Nagual Aug 03 '23 at 10:18

1 Answers1

1

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();
                    }
                  });
                  }
              });
            },
        ...),
Nabinda
  • 86
  • 4