简体   繁体   中英

Could not find the correct provider above this MyApp widget

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},
        ),
    );
  }
}

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(

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