Flutter NowPlaying 示例提供程序错误

Flutter NowPlaying Example Provider Error

我正在努力处理一些 flutter 代码,尤其是 streamprovider。

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

我在新的 flutter 项目中尝试了这段代码,但它一直在抛出错误。

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

错误代码如下:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following ProviderNotFoundException was thrown building Consumer(dirty): Error: Could not find the correct Provider above this Consumer 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 Consumer is under your MultiProvider/Provider. This usually happens when you are creating a provider and trying to read it immediately.

    For example, instead of:

      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>()),
        }
      ),   }   ```
    

示例中有几件事让我感到惊讶:

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

"To expose a newly created object, use the default constructor of a provider. Do not use the .value constructor if you want to create an object, or you may otherwise have undesired side effects"

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

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