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

使用Map.entries.firstWhere时Dart抛出类型错误问题排查

Dart类型错误排查:() => MapEntry<String?, String> 不兼容 () => MapEntry<String, String>?

问题代码

final langList = {
  null: "disabled",
  "ko": '한국어',
  "de": 'Deutsch',
  "ru": 'русский',
  "vi": 'Tiếng Việt',
  ...
}.entries.toList();


// in build method
Text(
  langList
      .firstWhere(
        (element) =>
            element.key ==
            translateClientKeyMap[user.clientKey],
        orElse: () =>
            const MapEntry<String?, String>(
                null, "disabled"),
      )
      .value,
  style: const TextStyle(
    color: Color(0xff000000),
    fontSize: 10.0,
  ),
)

报错信息

_TypeError (type '() => MapEntry<String?, String>' is not a subtype of type '(() => MapEntry<String, String>)?' of 'orElse')

问题原因

核心是Dart的类型推断自动收紧了langList的类型:
你定义的Map包含null作为key,但后续的key都是非null的String,Dart会默认把Map的key类型推断为String(而非你预期的String?),导致langList的实际类型是List<MapEntry<String, String>>。

此时firstWhere的orElse回调要求返回MapEntry<String, String>?,但你返回的是MapEntry<String?, String>,两种类型不兼容,触发类型错误。

解决方案

显式指定Map的泛型类型,强制key为String?,让langList的类型符合业务预期:

final langList = <String?, String>{
  null: "disabled",
  "ko": '한국어',
  "de": 'Deutsch',
  "ru": 'русский',
  "vi": 'Tiếng Việt',
  // ...
}.entries.toList();

这样langList的类型会被正确推断为List<MapEntry<String?, String>>,orElse返回的MapEntry<String?, String>就能匹配要求的类型,错误自然消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:02:50