首页 > 解决方案 > 如何在 Flutter 中更改 Radio 小部件的边框颜色?

问题描述

我目前拥有的

在此处输入图像描述

我想要达到的目标

在此处输入图像描述

我现在拥有的代码

Radio(
   value: 2,
   groupValue: val,
   onChanged: (value) {
   setState(() {
      val = value;
      });
   },
  activeColor: secondaryColor,)

标签: flutterflutter-layoutflutter-web

解决方案


无法自定义那么多单选按钮。按钮的唯一颜色参数是 fillColor。它将影响内圆和外圆。

如果您真的想要自定义外观,则需要构建自己的小部件。这是一个您可以自定义和改进的简单示例。您也可以尝试从 Flutter Radio 小部件的源代码开始。

class CustomRadio extends StatefulWidget {
  final int value;
  final int groupValue;
  final void Function(int) onChanged;
  const CustomRadio({Key? key, required this.value, required this.groupValue, required this.onChanged})
      : super(key: key);

  @override
  _CustomRadioState createState() => _CustomRadioState();
}

class _CustomRadioState extends State<CustomRadio> {
  @override
  Widget build(BuildContext context) {
    bool selected = (widget.value == widget.groupValue);

    return InkWell(
      onTap: () => widget.onChanged(widget.value),
      child: Container(
        margin: const EdgeInsets.all(4),
        padding: const EdgeInsets.all(4),
        decoration: BoxDecoration(shape: BoxShape.circle, color: selected ? Colors.white : Colors.grey[200]),
        child: Icon(
          Icons.circle,
          size: 30,
          color: selected ? Colors.deepPurple : Colors.grey[200],
        ),
      ),
    );
  }
}

结果 :

在此处输入图像描述


推荐阅读