简体   繁体   English

如何将 Provider 用于 Switch 小部件

[英]How to use Provider for a Switch widget

From the examples and those am seeing online, it looks like by by using Provider, we can avoid using Stateful Widgets for Switch() toggling.从示例和在线看到的示例来看,通过使用 Provider,我们可以避免使用 Stateful Widgets 进行 Switch() 切换。 I could achieve this by using a Stateful widget by having a global variable which I could set via setState().我可以通过使用一个有状态小部件来实现这一点,方法是使用一个全局变量,我可以通过 setState() 设置该变量。

An example: https://www.tutorialkart.com/flutter/flutter-switch/一个例子:https://www.tutorialkart.com/flutter/flutter-switch/

But can I achieve this as a stateless widget using Provider for a Switch Widget?但是我可以使用 Provider for a Switch Widget 作为无状态小部件来实现这一点吗?

This is my Switch widget:这是我的 Switch 小部件:

Switch(
  inactiveTrackColor: Colors.greenAccent,
  onChanged: (bool isNoti) {
    Provider.of<Data>(context, listen: false).toggleNotification(isNotifiable: !isNoti);
    print('Noti: $isNoti'); // always prints false
    print('Noti: ${Provider.of<Data>(context, listen: false).isNotifiable}'); // always prints true
  },
  value: Provider.of<Data>(context, listen: false).isNotifiable, // value doesn't change thus no toggle
),

Data class used by Provider. Provider 使用的数据类。

class Data extends ChangeNotifier {

  bool isNotifiable = false;

  void toggleNotification({bool isNotifiable = true}) {
    this.isNotifiable = isNotifiable;
    notifyListeners();
  }
}

Just to show it in completion, I do wrap it in ChangeNotifierProvider.只是为了在完成时显示它,我将它包装在 ChangeNotifierProvider 中。

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Data>(
      create: (context) => Data(),
      child: ListTile(
        leading: Icon(Icons.notifications),
        title:  Text('Notifications'),
        trailing: Switch(
          inactiveTrackColor: Colors.greenAccent,
          onChanged: (bool isNoti) {
            Provider.of<Data>(context, listen: false).toggleNotification(isNotifiable: !isNoti);
            print('Noti: $isNoti');
            print('Noti Provider: ${Provider.of<Data>(context, listen: false).isNotifiable}');
          },
          value: Provider.of<Data>(context, listen: false).isNotifiable,
        ),
      ),
    );
  }
}

Always get following output when I click the toggle.当我单击切换时,始终获得以下输出。

Noti: false
Noti Provider: true

Please advice.请指教。 Thank you.谢谢你。

I think I found your mistake, You've done everything right expect your switch is not rebuilding and the mistake here is that you've mentioned so that it should not rebuild.我想我发现了你的错误,你做的一切都是正确的,希望你的交换机不会重建,这里的错误是你已经提到了,所以它不应该重建。


trailing: Switch(
          inactiveTrackColor: Colors.greenAccent,
          onChanged: (bool isNoti) {
            Provider.of<Data>(context, listen: false).toggleNotification(isNotifiable: !isNoti);
            print('Noti: $isNoti');
            print('Noti Provider: ${Provider.of<Data>(context, listen: false).isNotifiable}');
          },
          value: Provider.of<Data>(context).isNotifiable,  // remove `listen: false` 
        ),

As value is what your switch depends on to rebuild.因为价值是您的交换机重建所依赖的。 But the provider is not listening to changed because you've mentioned listen: false .但是提供者没有监听更改,因为您已经提到了listen: false

Use

  • Provider.of<Data>(context, listen: false) when you are reading data such as in callbacks. Provider.of<Data>(context, listen: false)当您在回调中读取数据时。
  • Provider.of<Data>(context) use this when your widget needs to rebuild by listening to the changes Provider.of<Data>(context)当您的小部件需要通过监听更改来重建时使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更改 Stateful Widget 中 Switch 的 state,从 Provider 检索数据? - How to change the state of a Switch in a Stateful Widget, retrieving data from a Provider? 如何使用 MultiBlocProvider 并在子小部件中传递多个提供程序? - How to use MultiBlocProvider and pass multiple provider in a child widget? 如何在 Flutter 中使用 Provider 切换明暗主题? - How to use a switch to change between light and dark theme with Provider in Flutter? 如何在 flutter Provider 中为单个小部件使用多个消费者 - How to use multiple Consumers for a single widget in flutter Provider 如何在 flutter 中使用提供者 state 管理的可关闭小部件 - How to use dismissible widget with provider state management in flutter 如何访问一个Widget之外的provider? - How acess provider outside a Widget? 如果我使用 Switch 小部件上的新 val 更改 state,如何使用 Function 回调? - How to use Function callback if i'm use to change state with new val on Switch widget? 如何使用 Provider 为 PageView() 提供一个块,而无需每次切换页面时孩子都重新订阅? - How can I use Provider to provide a bloc to a PageView() without the child resubscribing everytime I switch page? 如何在小部件测试中包括提供者? - How to include a Provider(s) within widget testing? 如何通过提供程序在特定小部件中调用方法 - How to call method in specific widget by provider
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM