I have taken the below code from How to create a checkbox using listview which checks all the items when one item is checked. how do i fix the code to not to check all the items?
class CheckBoxInListView extends StatefulWidget {
@override
_CheckBoxInListViewState createState() => _CheckBoxInListViewState();
}
class _CheckBoxInListViewState extends State<CheckBoxInListView> {
bool _isChecked = false;
List<String> _texts = [
"InduceSmile.com",
"Flutter.io",
"google.com",
"youtube.com",
"yahoo.com",
"gmail.com"
];
@override
Widget build(BuildContext context) {
return ListView(
padding: EdgeInsets.all(8.0),
children: _texts
.map((text) => CheckboxListTile(
title: Text(text),
value: _isChecked,
onChanged: (val) {
setState(() {
_isChecked = val;
});
},
))
.toList(),
);
}
}
Just make a List of '_isChecked' variable and use that.
class CheckBoxInListView extends StatefulWidget {
@override
_CheckBoxInListViewState createState() => _CheckBoxInListViewState();
}
class _CheckBoxInListViewState extends State<CheckBoxInListView> {
List<String> _texts = [
"InduceSmile.com",
"Flutter.io",
"google.com",
"youtube.com",
"yahoo.com",
"gmail.com"
];
List<bool> _isChecked;
@override
void initState() {
super.initState();
_isChecked = List<bool>.filled(_texts.length, false);
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: _texts.length,
itemBuilder: (context, index) {
return CheckboxListTile(
title: Text(_texts[index]),
value: _isChecked[index],
onChanged: (val) {
setState(
() {
_isChecked[index] = val;
},
);
},
);
},
);
}
}
you should have a list for is checked, and assign them individually to each item.
class CheckBoxInListView extends StatefulWidget {
@override
_CheckBoxInListViewState createState() => _CheckBoxInListViewState();
}
class _CheckBoxInListViewState extends State<CheckBoxInListView> {
final List<SimpleModel> _items = <SimpleModel>[
SimpleModel('InduceSmile.com', false),
SimpleModel('Flutter.io', false),
SimpleModel('google.com', false),
SimpleModel('youtube.com', false),
SimpleModel('yahoo.com', false),
SimpleModel('gmail.com', false),
];
@override
Widget build(BuildContext context) => ListView(
padding: const EdgeInsets.all(8),
children: _items
.map(
(SimpleModel item) => CheckboxListTile(
title: Text(item.title),
value: item.isChecked,
onChanged: (bool val) {
setState(() => item.isChecked = val);
},
),
)
.toList(),
);
}
class SimpleModel {
String title;
bool isChecked;
SimpleModel(this.title, this.isChecked);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With