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

Dart类型转换报错:_InternalLinkedHashMap无法转Map<DateTime, List<Account>>

错误原因

Dart的Map.map()方法默认返回泛型为<dynamic, dynamic>的_InternalLinkedHashMap,即使内部返回的MapEntry键值对类型符合要求,外层Map的泛型也不会自动匹配。直接用as对泛型不匹配的Map做强转就会触发该异常。

另外注意原代码存在两处拼写错误,如果未修正也会引发编译问题:

  • 第二行的encodingTasks应为第一行定义的encodingaccounts
  • 返回MapEntry时写的convertedaccountsype少了字母T,正确为convertedAccountsType

解决方案

有两种常用的修复方式,可按需选择:

方式1:使用cast方法显式转换泛型

该方法不会额外拷贝数据,仅做泛型声明,性能损耗更低,修正后完整代码如下:

var encodingaccounts = json.decode(gettingAccounts!);
var encodedAccounts = encodingaccounts.map((dateTime, Accounts) {
    List<Account> convertedAccountsType = [];
    for (var account in Accounts) {
      String _summary = account['summary'];
      String _description = account['description'];
      String _category = account['category'];
      bool _isDone = account['isDone'];
      convertedAccountsType.add(Account(_summary,
          category: _category, description: _description, isDone: _isDone));
    }
    return MapEntry(DateTime.parse(dateTime), convertedAccountsType);
  });
// 替换原来的强转为cast方法转换
_accounts = encodedAccounts.cast<DateTime, List<Account>>();

方式2:用Map.fromEntries构造指定泛型的新Map

该方法会基于现有Entry重新生成一个新的Map,类型安全度更高,适合需要生成新对象的场景:

// 前面的map转换逻辑不变,仅修改最后赋值逻辑即可
_accounts = Map<DateTime, List<Account>>.fromEntries(encodedAccounts.entries);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:36:02