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

Flutter新手求助:如何创建带国旗与国名的单个单选按钮?

实现带国旗的单个国家单选按钮

你当前的代码存在几个小问题:groupValue和value大小写不统一、onChanged未实际更新选中状态,且缺少国旗元素。下面是调整后的完整实现方案:

方案一:使用Unicode国旗表情(最简单)

直接用国旗表情替代图片,无需额外资源配置:

import 'package:flutter/material.dart';

class CountryRadioPage extends StatefulWidget {
  const CountryRadioPage({super.key});

  @override
  State<CountryRadioPage> createState() => _CountryRadioPageState();
}

class _CountryRadioPageState extends State<CountryRadioPage> {
  // 存储选中的国家
  String? selectedCountry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text('Country & Currency',
                    style: TextStyle(
                        fontSize: 15,
                        color: Color(0xff8712bc),
                        decorationStyle: TextDecorationStyle.wavy)),
              ],
            ),
            RadioListTile(
              // 组合国旗表情和国名
              title: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text("🇧🇭"), // 巴林国旗Unicode表情
                  SizedBox(width: 8),
                  Text("Bahrain"),
                ],
              ),
              value: "Bahrain",
              groupValue: selectedCountry,
              onChanged: (value) {
                setState(() {
                  selectedCountry = value;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

方案二:使用本地国旗图片

如果需要自定义国旗样式,可使用本地图片:

  1. 先将国旗图片(如bahrain_flag.png)放入项目assets/images/目录,然后在pubspec.yaml中配置资源:
flutter:
  assets:
    - assets/images/bahrain_flag.png
  1. 替换代码中的标题部分:
title: Row(
  mainAxisSize: MainAxisSize.min,
  children: [
    Image.asset(
      'assets/images/bahrain_flag.png',
      width: 24,
      height: 16,
      fit: BoxFit.contain,
    ),
    SizedBox(width: 8),
    Text("Bahrain"),
  ],
),

关键细节说明

  • 用Row组合国旗与国名,实现需要的视觉效果
  • 通过selectedCountry变量管理选中状态,onChanged中调用setState更新状态,确保单选按钮选中状态同步
  • 国旗尺寸可通过width/height参数按需调整

内容的提问来源于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 06:30:53