Search code examples
flutterriverpodflutter-riverpod

How to solve "Do not use BuildContext across async gaps" in Riverpod's ConsumerWidget?


I get the warning "Do not use BuildContext across async gaps" when I use code like this:

await ref.read(testFutureProvider.notifier).doSomethingAsync();
Navigator.of(context).pop();

Normally it is possible to check the mounted property like this:

if(!mounted) return;

or

if(!context.mounted) return;

How can I avoid using BuildContext across async gaps in Riverpod in a ConsumerWidget?


Solution

  • The solution is to retrieve everything depending on your BuildContext before running async code:

    NavigatorState nav = Navigator.of(context);
    await ref.read(testFutureProvider.notifier).doSomethingAsync();
    nav.pop();