简体   繁体   中英

Flutter: Dependency Injecting using Multiprovider and Consumer in the same tree

I'm trying to inject instances of services (that have been created in the same tree level) into another provider. But down the tree when accessing the provider, I get ProviderNotFoundException exception. In the following code NotificationService depends on AuthService . Which needs to be passed in the constructor. Hence I inject it using Consumer and Provider.value as mentioned in the docs: https://pub.dev/documentation/provider/latest/provider/Consumer-class.html

Here is the pseudo-code:

return MultiProvider(
    providers: [
      Provider<AuthService>(
        create: (ctx) => AuthService(_storage),
        dispose: (ctx, v) => v.dispose(),
      ),
      Consumer<AuthService>(
        builder: (context, v, child) {
          return Provider.value(
              value: Provider<NotificationService>(
                create: (ctx) => NotificationService(v),
                dispose: (ctx, v) => v.dispose(),
              ),
              child: child
          );
        },
      )
    ],
    child: MyApp()
);

Somewhere down the tree line, When trying to access the NotificationService instance, I get ProviderNotFoundException :

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final NotificationService _ns = Provider.of<NotificationService>(context);
  }
}

Error:

I/flutter ( 4614): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 4614): The following ProviderNotFoundException was thrown building MyApp(dirty, dependencies:
I/flutter ( 4614): [_DefaultInheritedProviderScope<AuthService>]):
I/flutter ( 4614): Error: Could not find the correct Provider<NotificationService> above this MyApp Widget
I/flutter ( 4614): 
I/flutter ( 4614): To fix, please:
I/flutter ( 4614): 
I/flutter ( 4614):   * Ensure the Provider<NotificationService> is an ancestor to this MyApp Widget
I/flutter ( 4614):   * Provide types to Provider<NotificationService>
I/flutter ( 4614):   * Provide types to Consumer<NotificationService>
I/flutter ( 4614):   * Provide types to Provider.of<NotificationService>()
I/flutter ( 4614):   * Ensure the correct `context` is being used.
I/flutter ( 4614): 

I don't fully understand this, and I'm pretty sure there is a mistake in the above code. What am I doing wrong?

The way you used Provider.value is invalid. But you don't actually need Consumer + Provider . You can do:

MultiProvider(
  providers: [
    Provider(create: (_) => A()),
    Provider(create: (context) => B(Provider.of<A>(context, listen: false)),
  ],
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM