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

Flutter Map操作疑问:第二个函数为何修改原_filtersWithValue?

问题:第二个searchInFilter函数意外修改原始Map的原因分析

我编写了两个searchInFilter函数,第一个运行正常,但第二个会修改原始Map _filtersWithValue,请求帮忙解释第二个函数存在的错误。

两段函数代码

第一个函数(运行正常)

void searchInFilter(String MainKey, String searchKey) {
  final data = _filtersWithValue[MainKey]!.where((element) {
    return element.keys.first.toLowerCase().contains(searchKey.toLowerCase());
  }).toList();
  log(data.length.toString());
  _searchFiltersWithValue = _searchFiltersWithValue.map((key, value) {
    if (key == MainKey) {
      return MapEntry(key, data);
    }
    return MapEntry(key, value);
  });

  notifyListeners();
}

第二个函数(会修改原始Map)

void searchInFilter(String MainKey, String searchKey) {
  final data = _filtersWithValue[MainKey]!.where((element) {
    return element.keys.first.toLowerCase().contains(searchKey.toLowerCase());
  }).toList();
  log(data.length.toString());
  _searchFiltersWithValue[MainKey] = data;

  notifyListeners();
}

错误原因分析

两段代码的核心差异在于对_searchFiltersWithValue的修改方式:

  • 第一个函数使用_searchFiltersWithValue.map(...)生成了全新的Map实例,再将这个新Map赋值给_searchFiltersWithValue。这一步彻底切断了_searchFiltersWithValue与原始_filtersWithValue的引用关联,后续修改只会作用在新Map上,不会影响原始数据。
  • 第二个函数是直接在现有_searchFiltersWithValue实例上修改指定键的值。如果_searchFiltersWithValue初始化时是直接引用了_filtersWithValue(比如_searchFiltersWithValue = _filtersWithValue,而非创建独立副本),那这个赋值操作本质上是在修改原始_filtersWithValue对象本身——因为两者指向内存中的同一个Map,自然会导致原始数据被改动。

简单来说,第一个函数是创建新Map替换旧的,第二个是直接修改原Map的内容,若原Map和原始数据共享引用,就会触发意外修改。

内容的提问来源于stack exchange,提问作者muhammed basil.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:18:06