我正在尝试使用以下代码显示带有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参数始终为true。要查看已选中的CheckBox,我需要关闭对话框,然后再次打开它,单击该对话框不会立即更改。
我该如何解决?
答案 0 :(得分:0)
编辑: 正如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
});
您正在混合一些用于状态的列表。例如,您根据entityFilter列表中存在的行的实体来设置CheckBox的值,但这将始终为false,因为在onChanged()方法中,您仅使用 name 来自dropEntitiesList [index],而不是实体本身。您可以使用以下方法解决此问题:
value: globals.entitiesFilter.contains(dropEntitiesList[index].name),
(正如我所说的,您只在onChanged()方法中保存名称)。