flutter - 如果满足某些参数,我如何强制开关小部件仅更新
问题描述
我目前正在研究一个简单的开关列表,但我不希望它们能够同时关闭所有开关,这是否可能实现,如果我该怎么做?
解决方案
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;
}
}
},
),
);
}
}
推荐阅读
- c++ - 将对象推入向量时如何计算使用复制构造函数的次数?
- postgresql-10 - Hibernate 不会关闭空闲会话
- r - R Flexdashboard:无法在共享网络文件夹中运行
- sql-server - SQL Server:Datetimeoffset 到时间戳(精度为 6 位秒)
- c# - 为什么我的方法名称给我一个错误?
- ruby-on-rails - 我可以上传图像但无法查看它们。(Paperclip S3)
- android - 如何在 Android 活动中创建此自定义弹出消息?
- sql - INSERT 的目标列多于表达式
- javascript - 替换 javascript/jquery 中的占位符
- amazon-web-services - Bastion 机器后面的 RDS 实例的跨账户 DMS 复制