Search code examples
flutterprovider

Flutter NowPlaying Example Provider Error


I'm struggling with some flutter code especially streamprovider.

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

I tried this code with new flutter project but it keeps throwing errors.

Can you please help me solve this error?

Error code is like below:

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

Solution

  • There are a few things surprising me within the example:

    1. The example ommits the create: (_) => Example(), part. For this try adding: create: (_) => NowPlayingTrack(),
    2. Make sure to add initialValue: null, as the provider package since version 5.0.0-nullsafety requires initialData for both FutureProvider and StreamProvider.
    3. Refer to 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"

    This also means you should not use value: NowPlaying.instance.stream, to create your object but instead create a new object inside create (see 1.).

    1. The example is not specifying the concrete provider type, which might cause problems. Try this: StreamProvider<NowPlayingTrack>(...)