我已经使用了提供程序包来管理Flutter应用程序的状态,但是在使用它时面临许多问题。我已经定义了一个简单的提供程序,该提供程序具有一个布尔变量和一个更改变量值的方法
class LoadingModel with ChangeNotifier{
bool is_loading=false;
changeLoadingState(){
is_loading = !is_loading;
notifyListeners();
}}
现在我要从主页的MyApp类中调用提供程序中定义的changeLoadingState()方法,这是主页代码
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => LoadingModel(),
child: MaterialApp(
home:Scaffold(
body: Center(
child: Wrap(children: [
Column(children: [
RaisedButton(
child: Text("hide the progress"),
onPressed: () {
Provider.of(context,listen: false).changeLoadingState();
},
)
],)
],)
),
)
),
);
}
}
但是当我运行应用程序时,控制台显示
错误:在此MyApp窗口小部件上方找不到正确的提供程序
要解决,请:
context
。如果这些解决方案均无效,请在以下位置提交错误:https://github.com/rrousselGit/provider/issues
我如何解决这个问题???
尝试一下。希望您不会出错。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<LoadingModel>(
create: (context) => new LoadingModel(),
child: Consumer<LoadingModel>(builder: (context, loadingModel, _) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Wrap(
children: [
Column(
children: [
RaisedButton(
child: Text("hide the progress"),
onPressed: () {
loadingModel.changeLoadingState();
},
)
],
)
],
)),
));
}),
);
}
}