[英]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.