How to put multiple CheckboxListTile inside the ListView widget? I have already tried to do it but it caught some exceptions.
CodePudding user response:
first of all create class CheckBoxListTileModel (You can put anything in this class and you can define a List As needed) ex:
class CheckBoxListTileModel {
String title;
bool isCheck;
CheckBoxListTileModel({
required this.title,
required this.isCheck,
});
static List<CheckBoxListTileModel> getList() {
return <CheckBoxListTileModel>[
CheckBoxListTileModel(
title: "Android",
isCheck: true,
),
CheckBoxListTileModel(
title: "Flutter",
isCheck: false,
),
CheckBoxListTileModel(
title: "IOS",
isCheck: false,
),
CheckBoxListTileModel(
title: "PHP",
isCheck: false,
),
CheckBoxListTileModel(
title: "Node",
isCheck: false,
),
];
}
}
create a List is your page class
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
const TestPage({Key? key}) : super(key: key);
@override
State<TestPage> createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
List<CheckBoxListTileModel> checkBoxListTileModel =
CheckBoxListTileModel.getList();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 10,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Choose',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
ListView.builder(
shrinkWrap: true,
itemCount: checkBoxListTileModel.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
children: <Widget>[
CheckboxListTile(
title: Text(
checkBoxListTileModel[index].title,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
value: checkBoxListTileModel[index].isCheck,
onChanged: (bool? val) {
setState(() {
checkBoxListTileModel[index].isCheck = val!;
});
},
),
],
),
);
}),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () {
int i = 0;
checkBoxListTileModel.forEach((element) {
i ;
debugPrint('choice$i: ${element.isCheck}');
debugPrint('choice$i: ${element.title}\n');
});
},
child: const Text('Get Result'),
),
],
),
),
);
}
}
the button "get result" to see result in console (Not necessarily put it)
see result enter image description here
see console enter image description here
CodePudding user response:
multi_select_flutter this package does just that