【问题标题】:Provider function called but no change notified已调用提供程序函数但未通知更改
【发布时间】:2022-11-12 23:27:55
【问题描述】:

我的设置屏幕中有一个小部件,如下所示:

Widget autoplay()
{
   return  ChangeNotifierProvider<AutoplayToggle>(
               create: (context) => AutoplayToggle(),
               child: Consumer<AutoplayToggle>(
                  builder: (context, provider, child) {
                     return Container(
                               color: provider.isPause ? accent : primary,
                               width: 45,
                               child: Switch.adaptive(
                                   value: isPause,
                                   onChanged: (value) async {
                                      setState(() {
                                      isPause= value;
                                      });
                                   await UserPrefs.setAutoplay(isPause);
                                   provider.toggleAutoplay();
                                      },
                                    ),
                                  );
                                },
                              ),
                            ),
}

这是我的课:

class AutoplayToggle with ChangeNotifier{

   bool isPause = false;

   void toggleAutoplay()
   {
      isPause = !isPause;
      print(isPause);
      notifyListeners();
   }
}

我打印了几条语句进行调试,每次切换开关时都会调用该函数,因为值将从 false 变为 true,但是,它不会通知更改。对出了什么问题有任何想法吗?

【问题讨论】:

    标签: flutter provider


    【解决方案1】:

    你能试试加“懒惰的" : 假ChangeNotifierProvider?

    【讨论】:

      【解决方案2】:

      不要在 onChange 方法中使用 setState

      return ChangeNotifierProvider<AutoplayToggle>(
        create: (context) => AutoplayToggle(),
        child: Consumer<AutoplayToggle>(
          builder: (context, provider, child) {
            return Container(
             color: provider.isPause ? accent : primary,
              width: 45,
              child: Switch.adaptive(
                value: provider.isPause,
                onChanged: (value) async {
                  await UserPrefs.setAutoplay(isPause);
                  provider.toggleAutoplay();
                },
              ),
            );
          },
        ),
      );
      

      【讨论】:

        猜你喜欢
        • 2020-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 2023-01-20
        相关资源
        最近更新 更多