78 lines
2.0 KiB
Dart
78 lines
2.0 KiB
Dart
|
import 'package:flutter/material.dart';
|
||
|
|
||
|
class MulButton extends StatefulWidget {
|
||
|
final List<Color> colors;
|
||
|
final Function(List<Color>) onSelectionChanged;
|
||
|
|
||
|
MulButton({
|
||
|
required this.colors,
|
||
|
required this.onSelectionChanged,
|
||
|
});
|
||
|
|
||
|
@override
|
||
|
_MulButtonState createState() => _MulButtonState();
|
||
|
}
|
||
|
|
||
|
class _MulButtonState extends State<MulButton> {
|
||
|
late List<bool> selectedColors;
|
||
|
|
||
|
@override
|
||
|
void initState() {
|
||
|
super.initState();
|
||
|
selectedColors = List.generate(widget.colors.length, (index) => false);
|
||
|
}
|
||
|
|
||
|
void updateSelection(int index, bool value) {
|
||
|
setState(() {
|
||
|
selectedColors[index] = value;
|
||
|
List<Color> selected = [];
|
||
|
for (int i = 0; i < selectedColors.length; i++) {
|
||
|
if (selectedColors[i]) {
|
||
|
selected.add(widget.colors[i]);
|
||
|
}
|
||
|
}
|
||
|
widget.onSelectionChanged(selected); // 通知父组件
|
||
|
});
|
||
|
}
|
||
|
|
||
|
@override
|
||
|
Widget build(BuildContext context) {
|
||
|
return Wrap(
|
||
|
spacing: 8.0, // 水平间距
|
||
|
runSpacing: 4.0, // 垂直间距
|
||
|
alignment: WrapAlignment.start,
|
||
|
children: List.generate(widget.colors.length, (index) {
|
||
|
return Row(
|
||
|
mainAxisSize: MainAxisSize.min,
|
||
|
children: [
|
||
|
Checkbox(
|
||
|
value: selectedColors[index],
|
||
|
onChanged: (bool? value) {
|
||
|
if (value != null) {
|
||
|
updateSelection(index, value);
|
||
|
}
|
||
|
},
|
||
|
activeColor: widget.colors[index],
|
||
|
shape: RoundedRectangleBorder(
|
||
|
borderRadius: BorderRadius.circular(4), // 设置边角
|
||
|
),
|
||
|
),
|
||
|
Text(
|
||
|
colorToString(widget.colors[index]),
|
||
|
style: TextStyle(color: widget.colors[index]),
|
||
|
),
|
||
|
],
|
||
|
);
|
||
|
}),
|
||
|
);
|
||
|
}
|
||
|
|
||
|
String colorToString(Color color) {
|
||
|
if (color == Colors.blue) return 'Blue';
|
||
|
if (color == Colors.red) return 'Red';
|
||
|
if (color == Colors.green) return 'Green';
|
||
|
if (color == Colors.orange) return 'Orange';
|
||
|
return 'Unknown Color';
|
||
|
}
|
||
|
}
|