[英]ListView ListTile Switches toggle simultaneously in Flutter
I have a ListView
of ListTile
's with trailing Switch
'es.我有一个
ListTile
的ListView
和尾随Switch
的。 My problem is when I toggle any switch, other switches toggle too, although they shouldn't.我的问题是当我切换任何开关时,其他开关也会切换,尽管它们不应该切换。
Here's the look:这是外观:
Here's the code (with clutter removed):这是代码(去除了杂乱):
//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;
});
},
),
);
},
);
}
}
This happens because List.filled()
creates a list where all the elements are actually using the same object.发生这种情况是因为
List.filled()
创建了一个列表,其中所有元素实际上都使用相同的 object。 In other words, your scheduleList has the same object over and over again, not different objects.换句话说,您的 scheduleList 一遍又一遍地具有相同的 object,而不是不同的对象。 To create a new object for each index, use
List.generate()
instead.要为每个索引创建一个新的 object,请改用
List.generate()
。
Just replace your //Init list of programs
code with this and you're good to go:只需用这个替换您的
//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.