You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何制作如图所示的Flutter单个单选按钮?寻求技术帮助

实现自定义样式的单选按钮

你当前用的RadioListTile默认样式和目标效果有差距,我们可以通过自定义容器+Radio组件来实现图中的样式,具体实现代码如下:

// 先定义选中状态的变量
String selectedCountry = "Bahrain";

// 自定义单选按钮组件
Container(
  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(10),
    // 根据选中状态切换边框颜色
    border: Border.all(
      color: selectedCountry == "Bahrain" ? Colors.blue : Colors.grey.shade300,
      width: 2,
    ),
    // 选中时添加浅蓝背景
    color: selectedCountry == "Bahrain" ? Colors.blue.shade50 : Colors.transparent,
  ),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      // 国旗+文本区域
      Row(
        children: [
          CountryFlags.flag(
            'bh',
            width: 20,
            height: 20,
            borderRadius: 5,
          ),
          SizedBox(width: 8), // 国旗和文本之间的间距
          Text("Bahrain"),
        ],
      ),
      // 单选按钮组件
      Radio<String>(
        value: "Bahrain",
        groupValue: selectedCountry,
        activeColor: Colors.blue, // 选中时的颜色
        onChanged: (value) {
          setState(() {
            selectedCountry = value!;
          });
        },
      ),
    ],
  ),
)

关键细节说明:

  • 外层Container负责整体的圆角边框和背景色,通过选中状态动态切换样式,和你想要的效果匹配
  • 用Row分别布局左侧的国旗文本和右侧的单选按钮,MainAxisAlignment.spaceBetween让两边内容对齐
  • Radio组件自定义了选中颜色,点击时更新selectedCountry变量来触发状态切换

如果需要多个国家选项,可以把这段代码封装成一个可复用的函数,传入国旗代码、国家名称等参数,循环生成即可。

内容的提问来源于stack exchange,提问作者Priya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:16:36