checkbox - 在 onChanged 回调中 CheckBox 值始终为真
问题描述
我正在尝试使用以下代码显示带有 CheckBoxes 的 ListView 的 AlertDialog:
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(' ', textAlign: TextAlign.right,),
content: Directionality(
textDirection: TextDirection.rtl,
child: Container(
height: 300.0,
width: 300.0,
child: new ListView.builder(
shrinkWrap: true,
itemCount: dropEntitiesList.length,
itemBuilder: (BuildContext context, int index) {
return new Row(
children: [
new Checkbox(
value: globals.entitiesFilter.contains(dropEntitiesList[index]),
onChanged: (bool newValue) {
setState(() {
dropEntitiesList[index].isClicked = !dropEntitiesList[index].isClicked;
if (dropEntitiesList[index].isClicked){
globals.entitiesFilter.add(dropEntitiesList[index].name);
}else{
globals.entitiesFilter.remove(dropEntitiesList[index].name);
}
});
print(globals.entitiesFilter);
}),
new Text(
dropEntitiesList[index].name,
style: TextStyle(fontSize: 16.0),
),
],
);
}),
),
),
actions: <Widget>[
new FlatButton(
child: new Text('انتهيت'),
onPressed: () {
Navigator.of(context).pop(true);
}),
new FlatButton(
child: new Text('إلغاء'),
onPressed: () {
Navigator.of(context).pop(false);
},
)
],
);
onChanged 的 newValue 参数始终为真。要查看选中的复选框,我需要关闭对话框然后再次打开它,单击时不会立即更改。
我该如何解决这个问题?
解决方案
编辑: 如showDialog()的文档所述,如果对话框需要更新,则需要使用 StatefulBuilder。因此,将您的 Directionality 小部件包装在 StatefulBuilder 中:
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(' ', textAlign: TextAlign.right,),
content: StatefulBuilder(builder: (BuildContext context, StateSetter stateUpdater) {
return Directionality(..rest of code
}
在 onChange() 回调内部,然后使用 StateSetter 参数更新状态:
stateUpdater(() {
dropEntitiesList[index].isClicked = !dropEntitiesList[index].isClicked;
// rest of the code
});
您正在混合用于状态的一些列表。例如,您根据entitiesFilter 列表中存在的行的实体设置CheckBox 的值,但这将始终为false,因为在onChanged() 方法中,您仅使用dropEntitiesList[index]中的名称更新entitiesFilter 列表而不是实体本身。您可以使用以下方法解决此问题:
value: globals.entitiesFilter.contains(dropEntitiesList[index].name),
(正如我所说,您只在 onChanged() 方法中保存名称)。
推荐阅读
- php - PHP - shell_exec 的替代品
- google-cloud-platform - Google Cloud Composer - 让 Cloud Function 成为另一个 Cloud Function 的下游依赖项
- spring-boot - 如何编写代码以通过spring boot api查看s3存储桶图像
- java - 从 java 调用 Kotlin 函数会导致 java.lang.NoClassDefFoundError: kotlin/TypeCastException (String Arrays)
- c++ - C++ LRU 缓存 - 需要有关如何提高速度的建议
- javascript - 覆盖 Material-UI 选择样式
- java - 使用 Mongo CSFLE (mongodb-crypt) 时 /tmp 挂载为 noexec 时的 java.lang.UnsatisfiedLinkError
- javascript - 在javascript中重命名json的每个键
- oracle-cloud-infrastructure - Oracle 云基础设施 - 跨区域复制 Vault
- mysql - 选择名称 WHERE 指向正方形