简体   繁体   中英

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

I do not understand why the following code generates the error? According to me the provider is an ancestor to MaterialApp and it should work? What am I missing?

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        new Provider<Color>(create: (_) => Colors.amber)
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Provider.of<Color>(context),
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      )
    );
  }
}

Provider initially in build method. You don't access to use provider value because provider inits context, but you tried to use provider.of(context) in the same place. If you use another state(view), you should use it.

Example code : https://gist.github.com/VB10/358dc944e5a86b58db2d898eaa1b5ea6

提供者样本

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