0

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?

maxmitz
  • 258
  • 1
  • 4
  • 17

3 Answers3

2

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();
Thomas
  • 2,375
  • 2
  • 17
  • 32
  • Could you explain why this is better than registering a callback when the future completes with ".then(...)" like in Slobodan's answer? – maxmitz Dec 21 '22 at 23:09
  • 1
    It is the same thing from a logical point of view. In my opinion, async/await is just way more readable and doesn't nest, so I always prefer it. – Thomas Dec 22 '22 at 13:15
2

Try this:

ref.read(testFutureProvider.notifier).doSomethingAsync().then((value){
    Navigator.of(context).pop();
})
Slobodan M.
  • 31
  • 1
  • 3
  • Could you explain why this is better than retrieving the navigator state like in Thomas's answer? – maxmitz Dec 21 '22 at 23:07
  • 1
    Hm, it isn’t really much better. Other than the fact that you’re using the latest snapshot of the context instead of retrieving it first (if this is of any importance for your use case). Also, I find this more readable because it’s something we already saw so many times, that this simple nesting isn’t really a problem. However, I do prefer async/await in any other context. – Slobodan M. Dec 23 '22 at 00:58
-1

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.

My Car
  • 4,198
  • 5
  • 17
  • 50