Search code examples
flutterprovider

How get a item from a sub provider - flutter


Its possible create a "global" provider to get it in sub contexts, ex:

MultiProvider(
  providers: [
      Provider<IMyMainClass>(create: (_) => MainClass()),
  
  ],
  child: MaterialApp(
    debugShowCheckedModeBanner: false,
    routes: {
      '/routeA': (c) => const PageA(c.read<IMyMainClass>()),

      '/routeB': (c) => const PageB(c.read<IMyMainClass>()),

      '/routeC': (c) => MultiProvider(
        providers: [
            Provider<IOtherClass>(create: (c) => OtherClass(c.read<IMyMainClass>())),
  
        ],
        child: PageC()
      )
    },
  )
)

I tried do something like this and get this error:

Error: Could not find the correct Provider<IMyMainClass>
above this _InheritedProviderScope<IMyMainClass?> Widget

This happens because you used a `BuildContext` that does not
include the provider

Solution

  • The error is because in my real case I don't cast the provider with interface:

    Provider<Interface>(create: (_) => Class())
    

    And then when I tried get it with context.read() the error occurs, I believe its because he trying automatic cast to my Class and not the interface.