[英]ListView ListTile Switches toggle simultaneously in Flutter
我有一个ListTile
的ListView
和尾随Switch
的。 我的问题是当我切换任何开关时,其他开关也会切换,尽管它们不应该切换。
这是外观:
这是代码(去除了杂乱):
//Schedule program class
class ScheduleProgram {
bool enabled;
bool isStart;
TimeOfDay time;
int duration;
List<bool> dow;
ScheduleProgram(
{this.enabled, this.isStart, this.time, this.duration, this.dow});
}
//Init list of programs
List<ScheduleProgram> scheduleList =
List<ScheduleProgram>.filled(10,
ScheduleProgram(
enabled: false,isStart: false,time: TimeOfDay(minute: 0, hour: 0),
duration: 0,dow: [false, false, false, false, false, false, false]),
growable: false );
...
//And now build the list
int _selectedProgramIndex = 0;
ListView _generateTaskButtonList(BuildContext context) {
return ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return SizedBox(height: 10);
},
itemCount: 10,
itemBuilder: (BuildContext context, int index) {
return ClipRRect(
child: ListTile(
selected: index == _selectedProgramIndex,
leading: IconButton(
icon: const Icon(Icons.edit, size: 30),
onPressed: () {
setState(() {
log("Edit $index pressed");
});
},
),
title: Text('P' + index.toString() + ':'),
subtitle: Text('-'),
trailing: Padding(
child: Transform.scale(
child: Switch(
onChanged: (v) {
setState(() {
scheduleList[index].enabled = v;
log("P$index is $v, scheduleList enabled = " +
scheduleList[index].enabled.toString());
});
},
value: scheduleList[index].enabled,
),
),
),
onTap: () {
log('Tapped #' + index.toString());
setState(() {
_selectedProgramIndex = index;
});
},
),
);
},
);
}
}
发生这种情况是因为List.filled()
创建了一个列表,其中所有元素实际上都使用相同的 object。 换句话说,您的 scheduleList 一遍又一遍地具有相同的 object,而不是不同的对象。 要为每个索引创建一个新的 object,请改用List.generate()
。
只需用这个替换您的//Init list of programs
您就可以使用 go:
//Init list of programs
List<ScheduleProgram> scheduleList = List<ScheduleProgram>.generate(
10,
(index) => ScheduleProgram(
enabled: false,
isStart: false,
time: TimeOfDay(minute: 0, hour: 0),
duration: 0,
dow: [false, false, false, false, false, false, false]),
growable: false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.