68 lines
1.7 KiB
Dart
68 lines
1.7 KiB
Dart
|
import 'package:flutter/material.dart';
|
||
|
|
||
|
class SingleButton extends StatefulWidget {
|
||
|
final List<Color> colors;
|
||
|
final Function(Color) onSelectionChanged;
|
||
|
|
||
|
SingleButton({
|
||
|
required this.colors,
|
||
|
required this.onSelectionChanged,
|
||
|
});
|
||
|
|
||
|
@override
|
||
|
_SingleButtonState createState() => _SingleButtonState();
|
||
|
}
|
||
|
|
||
|
class _SingleButtonState extends State<SingleButton> {
|
||
|
late Color selectedColor;
|
||
|
|
||
|
@override
|
||
|
void initState() {
|
||
|
super.initState();
|
||
|
selectedColor = widget.colors[0]; // 默认选中第一个颜色
|
||
|
}
|
||
|
|
||
|
void updateSelection(Color color) {
|
||
|
setState(() {
|
||
|
selectedColor = color;
|
||
|
widget.onSelectionChanged(color); // 通知父组件
|
||
|
});
|
||
|
}
|
||
|
|
||
|
@override
|
||
|
Widget build(BuildContext context) {
|
||
|
return Row(
|
||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||
|
children: List.generate(widget.colors.length, (index) {
|
||
|
return Row(
|
||
|
mainAxisSize: MainAxisSize.min,
|
||
|
children: [
|
||
|
Radio<Color>(
|
||
|
value: widget.colors[index],
|
||
|
groupValue: selectedColor,
|
||
|
onChanged: (Color? value) {
|
||
|
if (value != null) {
|
||
|
updateSelection(value);
|
||
|
}
|
||
|
},
|
||
|
activeColor: widget.colors[index],
|
||
|
),
|
||
|
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';
|
||
|
}
|
||
|
}
|