map
to maintain the state创建 map :
final Map<int, bool> _state = {};
然后,判断该索引的值是否为true
/false
:
return ListView.builder(itemBuilder: (context, index) {
return CheckboxListTile(
value: _state[index] ?? false,
onChanged: (value) {
setState(() {
_state[index] = value!;
});
},
title: Text(_data[index].text),
);
});
class CheckBoxModel {
bool isChecked = false;
String text = "";
CheckBoxModel({required this.isChecked, required this.text});
}
然后,生成包含30个小部件的列表:
final _data = List.generate(
30, (index) => CheckBoxModel(isChecked: false, text: "Item $index"));
现在,使用ListView.builder
并基于index
更新相应的值:
class Testing extends StatefulWidget {
const Testing({Key? key}) : super(key: key);
@override
State<Testing> createState() => _TestingState();
}
class _TestingState extends State<Testing> {
@override
Widget build(BuildContext context) {
return ListView.builder(itemBuilder: (context, index) {
return CheckboxListTile(
value: _data[index].isChecked,
onChanged: (value) {
setState(() {
_data[index].isChecked = value!;
});
},
title: Text(_data[index].text),
);
});
}
}