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

Flutter:为何SimpleMap无法使用_countryCode变量设置国家颜色?

问题原因

SMapWorldColors是预定义类,它的命名参数是固定的国家代码(比如uS、bE),这些参数是编译时确定的,不能用变量(比如_countryCode)作为参数名,所以直接写_countryCode: Colors.green会提示“命名参数未定义”。

解决方案

不要依赖SMapWorldColors的命名参数实现动态颜色,直接构造Map<String, Color>:

  • 先创建包含固定自定义颜色的基础Map
  • 若_countryCode有值,将对应国家代码作为key,添加/覆盖颜色到Map中
  • 将这个动态生成的Map传给SimpleMap的colors参数

注意:要确保_countryCode的格式和SimpleMap使用的国家代码格式一致(比如SMapWorld通常用大写代码,需将获取到的代码转为大写)。

修改后的完整代码
class WorldMap extends StatefulWidget {
  const WorldMap({super.key});

  @override
  State<WorldMap> createState() => _WorldMapState();
}

class _WorldMapState extends State<WorldMap> {
  String _countryName = '';
  String _countryCode = '';
  List<Map<String, String>> countries = [
    {"name": "Afghanistan", "code": "AF"},
    {"name": "Åland Islands", "code": "AX"},
    {"name": "Albania", "code": "AL"},
    {"name": "Algeria", "code": "DZ"},
    {"name": "American Samoa", "code": "AS"},
  ];

  @override
  Widget build(BuildContext context) {
    // 构造动态颜色Map
    final colorMap = <String, Color>{
      'US': Colors.green,
      'BE': Colors.red,
    };
    // 动态添加选中国家的颜色
    if (_countryCode.isNotEmpty) {
      colorMap[_countryCode.toUpperCase()] = Colors.green;
    }

    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            TextField(
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                hintText: "Enter the name of a country",
              ),
              onSubmitted: (String userInput) {
                setState(() {
                  _countryName = userInput;
                  // 重置之前的选中状态
                  _countryCode = '';
                });
                for (var element in countries) {
                  if (element["name"] == _countryName) {
                    setState(() {
                      _countryCode = element["code"]!;
                    });
                    print(_countryCode);
                    // 找到匹配项后退出循环
                    break;
                  }
                }
              },
            ),
            const SizedBox(height: 35),
            SimpleMap(
              instructions: SMapWorld.instructions,
              defaultColor: Colors.grey,
              colors: colorMap,
            ),
          ],
        ),
      ),
    );
  }
}
补充说明
  • 初始化_countryName和_countryCode为空字符串,避免未初始化的运行时错误
  • 用户输入新国家名时重置_countryCode,避免残留之前的选中状态
  • 找到匹配国家后添加break,提升循环效率
  • 国家代码转大写是适配SMapWorld的常规格式,可根据实际情况调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:57:22