一、效果图
二、主要代码
import 'package:company_manage_flutter/xcClass/dicDataProp.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class CheckListWidget extends StatefulWidget {
final List<Map<String, dynamic>> list;
final Function? onChanged;
final DicDataProp props;
Map<String, dynamic>? initValue;
CheckListWidget(
{super.key,
required this.list,
this.onChanged,
this.props = const DicDataProp(),
this.initValue});
@override
State<CheckListWidget> createState() => CheckListWidgetState();
}
class CheckListWidgetState extends State<CheckListWidget> {
RxMap<String, dynamic> selected = <String, dynamic>{}.obs;
@override
void initState() {
super.initState();
selected.value = widget.initValue ?? {};
}
@override
Widget build(BuildContext context) {
return buildCheckList(widget.list, widget.onChanged, props: widget.props);
}
void test() {
print('test-组件内的方法');
}
Widget buildCheckList(List<Map<String, dynamic>> list, Function? onChanged,
{DicDataProp? props}) {
String label = props?.label ?? 'label';
String value = props?.value ?? 'value';
return Obx(() => Container(
width: Get.width,
child: Column(
children: list.asMap().entries.map((entry) {
int index = entry.key;
dynamic item = entry.value;
return Column(
children: [
GestureDetector(
onTap: () {
selected?.value = item;
if (onChanged != null) {
onChanged(item);
}
},
child: Container(
width: Get.width,
decoration: BoxDecoration(
color: Colors.blue.withOpacity(0),
),
padding: const EdgeInsets.symmetric(
vertical: 16, horizontal: 16),
child: Row(
children: [
Icon(
(selected?.value[value] ?? '') == item[value]
? Icons.check_circle
: Icons.circle_outlined,
size: 22,
color:
(selected?.value[value] ?? '') == item[value]
? Color.fromRGBO(50, 73, 223, 1)
: Color.fromRGBO(21, 23, 30, 0.40)),
SizedBox(width: 6),
Text(
item[label] ?? "",
style: TextStyle(
fontSize: 16,
),
),
],
),
)),
Divider(
height: 1,
color: index + 1 == list.length
? Color.fromRGBO(128, 130, 145, 0)
: Color.fromRGBO(128, 130, 145, 0.20),
),
],
);
}).toList(),
)));
}
}
三、使用
final checkListWidgetKey = GlobalKey<CheckListWidgetState>();
CheckListWidget(
key: checkListWidgetKey,
list: bottomSheetList,
onChanged: (value) {
print("CheckListWidget:${value}");
},
initValue: const {'id': '18', 'name': '仓库1'},
props: DicDataProp(label: 'name', value: 'id'),
),
buildButtonWidget('调用组件的方法、获取值', onPressed: () {
print(
'调用组件的方法、获取值 = ${checkListWidgetKey.currentState?.selected}');
checkListWidgetKey.currentState?.test();
}),