Flutter Provider的方法不能从类中调用

问题描述 投票:0回答:1

我已经使用了提供程序包来管理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窗口小部件上方找不到正确的提供程序

要解决,请:

  • 确保提供者是此MyApp小部件的祖先
  • 向提供者提供类型
  • 向消费者提供类型
  • 将类型提供给Provider.of()
  • 始终使用包导入。例如:`import'package:my_app / my_code.dart';
  • 确保使用正确的context

如果这些解决方案均无效,请在以下位置提交错误:https://github.com/rrousselGit/provider/issues

我如何解决这个问题???

flutter dart provider
1个回答
0
投票

尝试一下。希望您不会出错。

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();
                    },
                  )
                ],
              )
            ],
          )),
        ));
      }),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.