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

xmd2e60i  于 2024-01-04  发布在  Flutter
关注(0)|答案(2)|浏览(216)

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

  1. final adState = AdState(initialization: adsInitialization);
  2. runApp(
  3. Provider.value(
  4. value: adState,
  5. child: MyApp(email, password, language),
  6. ),
  7. );

字符串
'''
现在我有

  1. runApp(ProviderScope(
  2. child: MyApp(email, password, language),
  3. ));


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

  1. flutter: Error: Could not find the correct Provider<UserSettings> above this HomePage Widget
  2. This happens because you used a `BuildContext` that does not include the provider
  3. of your choice. There are a few common scenarios:
  4. - You added a new provider in your `main.dart` and performed a hot-reload.
  5. To fix, perform a hot-restart.
  6. - The provider you are trying to read is in a different route.
  7. Providers are "scoped". So if you insert of provider inside a route, then
  8. other routes will not be able to access that provider.
  9. - You used a `BuildContext` that is an ancestor of the provider you are trying to read.
  10. Make sure that HomePage is under your MultiProvider/Provider<UserSettings>.
  11. 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)。但是,我会在提供程序中初始化示例。

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

字符串

yi0zb3m4

yi0zb3m42#

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

  1. final container = ProviderContainer();
  2. // now you have access to container.read to perform any provider initializations prior to runApp.
  3. container.read(adStateProvider);
  4. // Use UncontrolledProviderScope instead of ProviderScope
  5. // and pass in the container.
  6. runApp(
  7. UncontrolledProviderScope(
  8. container: container,
  9. child: const MyApp(),
  10. ),
  11. );

字符串

展开查看全部

相关问题