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

Dart/Flutter中非const/final Map调用removeWhere报不可修改错误

问题:调用removeWhere()时抛出“Cannot modify unmodifiable map”错误

我编写了一个读取Google Sheet的函数,未将任何变量声明为final或const,但在Google Pixel 5模拟器运行时抛出错误。错误信息为“Unsupported operation: Cannot modify unmodifiable map”,出现在调用idMap.removeWhere()处。

代码实现:

static Future<List<Client>?> getRouteById({required String id}) async {

    // Get all routeIDs from client sheet
    List<String>? routeIds = await clientSheet!.values.columnByKey('route');

    // Converts list to map with indices as keys
    Map<int, String> idMap = routeIds!.asMap();

    // Strips away all non relevant routeID's
    idMap.removeWhere((key, value) => value != id); // <- ERROR

    // Gets client data from each index
    List<Client> route = [];
    idMap.forEach((key, value) async {
      List<dynamic> clientList = await clientSheet!.values.row(key);
      route.add(Client(clientList));
    });
    return route;
  }

完整错误栈:

E/flutter (10996): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Unsupported operation: Cannot modify unmodifiable map
E/flutter (10996): #0      _UnmodifiableMapMixin.removeWhere (dart:collection/maps.dart:294:5)
E/flutter (10996): #1      SheetsAPI.getRouteById (package:bugman_route_v2/helper/sheetsAPI.dart:63:12)
E/flutter (10996): asynchronous suspension

请问我忽略了什么?(抱歉如果问题很明显,我还在学习中)


解答

核心原因:List.asMap()返回不可修改的Map

routeIds!.asMap()生成的是原列表的不可修改映射视图,它仅作为列表的索引-元素映射展示,不支持removeWhere()这类修改操作,这就是报错的直接原因。

修复方案

将不可修改的Map转换为可修改的普通Map,两种常用方式:

// 方式1:用Map.from包装
Map<int, String> idMap = Map.from(routeIds!.asMap());

// 方式2:用展开语法
Map<int, String> idMap = {...routeIds!.asMap()};

额外潜在问题修复

代码中forEach内的async回调不会等待异步任务完成,最终返回的route列表会是空的,建议改用for-in循环处理异步逻辑:

List<Client> route = [];
// 替换原forEach循环
for (var entry in idMap.entries) {
  List<dynamic> clientList = await clientSheet!.values.row(entry.key);
  route.add(Client(clientList));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:45:55