首页 > 解决方案 > 如果满足某些参数,我如何强制开关小部件仅更新

问题描述

我目前正在研究一个简单的开关列表,但我不希望它们能够同时关闭所有开关,这是否可能实现,如果我该怎么做?

标签: flutterdart

解决方案


List<bool>您可以使用内部跟踪哪些开关“打开”,StatefulWidget并根据从阵列中获得的其他开关的状态决定更改任何开关的状态,如下所示:

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  List<bool> switchStates;

  @override
  void initState() {
    switchStates = List<bool>(10)..fillRange(0, 10,false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 10,
      itemBuilder: (ctx, index) => Switch(
        value: switchStates[index],
        onChanged: (newValue){
          if(newValue)//user is trying to set switch state to true, so we don't check value of other switches as this action is always allowed
            {
            switchStates[index] = newValue;//on
            }
          else if(!newValue)//user is trying to set switch to false, so we do a check on all other switches before we turn it off
          {
            bool areAllOff = true;//suppose all are off
            for(final state in switchStates){
              if(state)//if at least one is on, so we can turn current switch off
              switchStates[index]=newValue;//off
              break;
            }
          }

        },
      ),
    );
  }
}

推荐阅读