【问题标题】:Flutter NowPlaying Example Provider ErrorFlutter NowPlaying 示例提供程序错误
【发布时间】:2021-11-07 10:08:39
【问题描述】:

我正在为一些颤动的代码而苦苦挣扎,尤其是 streamprovider。

https://pub.dev/packages/nowplaying/example

我用新的颤振项目尝试了这段代码,但它一直抛出错误。

你能帮我解决这个错误吗?

错误代码如下:

══╡ 小部件库发现异常 ╞═════════════════════════════════════════════════ ══════════ 以下 ProviderNotFoundException 被抛出建设 消费者(脏):错误:找不到正确的 此 Consumer Widget 上方的提供者

发生这种情况是因为您使用的 BuildContext 不包含 您选择的提供商。有几种常见的情况:

  • 您在 main.dart 中添加了一个新提供程序并执行了热重载。要修复,请执行热重启。

  • 您尝试读取的提供程序位于不同的路径中。

    提供者是“范围的”。因此,如果您在路线内插入提供者, 那么其他路由将无法访问该提供程序。

  • 您使用了BuildContext,它是您尝试读取的提供程序的祖先。

    确保消费者在您的 多提供者/提供者。这通常发生在 您正在创建一个提供程序并尝试立即读取它。

    例如,而不是:

      return Provider<Example>(
        create: (_) => Example(),
        // Will throw a ProviderNotFoundError, because `context` is associated
        // to the widget that is the parent of `Provider<Example>`
        child: Text(context.watch<Example>()),
      ),   }   ```
    
    consider using `builder` like so:
    
    ```   Widget build(BuildContext context) {
      return Provider<Example>(
        create: (_) => Example(),
        // we use `builder` to obtain a new `BuildContext` that has access to the provider
        builder: (context) {
          // No longer throws
          return Text(context.watch<Example>()),
        }
      ),   }   ```
    

【问题讨论】:

    标签: flutter provider


    【解决方案1】:

    这个例子中有几处让我吃惊:

    1. 该示例省略了create: (_) =&gt; Example(), 部分。 为此尝试添加:create: (_) =&gt; NowPlayingTrack(),
    2. 确保将initialValue: null, 添加为提供程序包,因为版本5.0.0-nullsafety 需要initialData for both FutureProvider and StreamProvider
    3. 参考provider docs:

    "要公开一个新创建的对象,请使用 提供者。如果要创建一个,不要使用 .value 构造函数 对象,或者你may otherwise have undesired side effects"

    这也意味着你不应该使用value: NowPlaying.instance.stream, 来创建你的对象,而是创建 在 create 中创建一个新对象(参见 1.)。

    1. 该示例未指定具体的提供程序类型,这可能会导致问题。试试这个:StreamProvider&lt;NowPlayingTrack&gt;(...)

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 2021-09-30
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      相关资源
      最近更新 更多