skip to Main Content

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?

3

Answers


  1. 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();
    
    Login or Signup to reply.
  2. Try this:

    ref.read(testFutureProvider.notifier).doSomethingAsync().then((value){
        Navigator.of(context).pop();
    })
    
    Login or Signup to reply.
  3. Try the following code:

    try {
      await ref.read(testFutureProvider.notifier).doSomethingAsync();
    } catch (e) {
      debugPrint(e);
    } finally {
      Navigator.of(context).pop();
    }
    

    await ref.read(testFutureProvider.notifier).doSomethingAsync().then((value) => Navigator.of(context).pop()).catchError((e) => debugPrint(e));
    

    I suggest you choose one of the two codes above as they both check for errors for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search