[英]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).
但是当我在 materialApp 中为主题使用状态变量时,这会引发错误(也重新启动)。 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.context
。 This will take member variable context not the above line written 'context' under the parameter of creare.这将采用成员变量上下文而不是上面写在 creare 参数下的 'context' 行。
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.用消费者包装您的材料应用程序并尝试一次此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.