简体   繁体   中英

context provided but throws error Could not find the correct Provider<Data> above this MyApp Widget Flutter

I am using provider for state management. The state variables works fine for other widgets. But when I use the state variable for theme in materialApp this throws me the error(restarted too). Also declared provider high in the tree.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Data>(
      create: (context) => Data(),
      child: MaterialApp(
        theme: Provider.of<Data>(context).current,
        home: Page1(),
        debugShowCheckedModeBanner: false,
      ),
    );
  }}

The Data Class:

class Data extends ChangeNotifier {
  String school = "xyz";
  String name = "samuel";
  int age = 123;
  int val = 0;
  String userinput = "";
  ThemeData current = ThemeData.dark();
  void increment() {
    val++;
    notifyListeners();
  }

  void display(String char) {
    userinput = char;
    notifyListeners();
  }
}

Actually when you use context, instead of this use this.context . This will take member variable context not the above line written 'context' under the parameter of creare.

void main(){
  runApp(ChangeNotifierProvider<Data>(
      create: (context) => Data(),
      child: MyApp(),
    ),);
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<Data>(
      builder: (context, appState, child) {
        return MaterialApp(
          theme: Provider.of<Data>(context).current,
          debugShowCheckedModeBanner: false,
          home: Page1(),
        );
      },
    );
  }
}

Wrap your material app with consumer and try this code once.

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