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

问题描述 投票:0回答:2

我正在将整个应用程序迁移到 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“值”?我对 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.

如有任何帮助,我们将不胜感激,谢谢!

flutter dart admob provider
2个回答
1
投票

Riverpod 中

Provider<AdState>.value(value: adState)
的等价物是
Provider<AdState>((ref) => adState)
。但是,我会像这样初始化提供程序内部的实例。

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

0
投票

鉴于我尝试做同样的事情,我遇到了这个问题。

这是我使用 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(),
    ),
  );
© www.soinside.com 2019 - 2024. All rights reserved.