Search code examples
flutterdartadmobprovider

Converting flutter adMob functionality from provider to riverpods


I'm migrating my whole app to riverpods and encountered one lasting error. Essentially, in my main.dart I used to have Provider.value such that:

final adState = AdState(initialization: adsInitialization);

runApp(
  Provider.value(
    value: adState,
    child: MyApp(email, password, language),
  ),
);

'''

And now I have

 runApp(ProviderScope(
  child: MyApp(email, password, language),
));

As specified in the riverpods docs. I was wondering what needs to be modified to pass the adstate 'value' like before? I'm a bit confused of what the Provider.value even did in the first place...

Here's the error I get

flutter: Error: Could not find the correct Provider<UserSettings> above this HomePage Widget

This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

- The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

- You used a `BuildContext` that is an ancestor of the provider you are trying to read.

  Make sure that HomePage is under your MultiProvider/Provider<UserSettings>.
  This usually happens when you are creating a provider and trying to read it immediately.

Any help is appreciated thank you!


Solution

  • The Riverpod equivalent of Provider<AdState>.value(value: adState) would be Provider<AdState>((ref) => adState). However, I would initialize the instance inside of the provider as such.

    final adState = Provider<AdState>((ref) {
      return AdState(initialization: adsInitialization);
    });