Could not find the correct provider above this MyApp widget

777 views Asked by At

I'm trying to use a provider in MaterialApp. I have a MultiProvider which is a parent of the MaterialApp.

When I try accessing the provider, I get the following error:

Error: Could not find the correct Provider above this MyApp Widget

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<RoutesProvider>(create: (context) => RoutesProvider()),
        ...
      ],
        child: MaterialApp(
          title: 'coolApp',
          // key: Provider.of<RoutesProvider>(context, listen: false).mainKey,
          initialRoute: '/home',
          routes: <String, WidgetBuilder>{...routes},
        ),
    );
  }
}
1

There are 1 answers

1
Jitesh Mohite On BEST ANSWER

Follow the below structure, ChangeNotifierProvider.value is the right way of assigning provider

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: RoutesProvider()),
        //.....
      ],
      child: MaterialApp(