[英]CheckboxListTile in ListView Flutter
How to put multiple CheckboxListTile inside the ListView widget?如何在 ListView 小部件中放置多个 CheckboxListTile? I have already tried to do it but it caught some exceptions.我已经尝试过这样做,但它遇到了一些异常。
first of all create class CheckBoxListTileModel (You can put anything in this class and you can define a List As needed) ex:首先创建类 CheckBoxListTileModel (你可以在这个类中放任何东西,你可以根据需要定义一个列表)例如:
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请参阅控制台在此处输入图像描述
multi_select_flutter这个包就是这样做的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.