dart 将flutter adMob功能从提供商转换为riverpods

xmd2e60i  于 5个月前  发布在  Flutter
关注(0)|答案(2)|浏览(71)

我正在将整个应用迁移到riverpods,遇到了一个持久的错误。本质上,在我的main.dart中,我曾经有Provider.value,这样:

final adState = AdState(initialization: adsInitialization);

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

字符串
'''
现在我有

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


正如在riverpods文档中所指定的那样。我想知道需要修改什么才能像以前一样传递adstate 'value'?我有点困惑Provider.value在第一时间做了什么。
这是我得到的错误

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.


任何帮助是赞赏谢谢!

6uxekuva

6uxekuva1#

Riverpod中Provider<AdState>.value(value: adState)的等价物是Provider<AdState>((ref) => adState)。但是,我会在提供程序中初始化示例。

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

字符串

yi0zb3m4

yi0zb3m42#

我遇到了这个问题,因为我试图做同样的事情。
这是我使用riverpod的方法。
因此,使用riverpod,您实际上可以在runApp(.)之前创建自己的ProviderContainer。

final container = ProviderContainer();

  // now you have access to container.read to perform any provider initializations prior to runApp.
  container.read(adStateProvider);

  // Use UncontrolledProviderScope instead of ProviderScope
  // and pass in the container.
  runApp(
    UncontrolledProviderScope(
      container: container,
      child: const MyApp(),
    ),
  );

字符串

相关问题