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

Flutter/Dart报错Unsupported operation:无法向不可修改列表添加元素

问题原因与解决方法

你的错误根源是构造函数中kategorienBool的默认参数用了const [false]——被const修饰的列表是不可修改的。即便类里定义的是List<bool>类型,当你没有显式给kategorienBool传值时,实例会使用这个不可变的const列表,调用add方法自然触发报错。

修复方案

方案1:直接修改默认参数为可变列表

把构造函数里的const [false]改成普通的可变列表,去掉const关键字:

Produkt({
    required this.zutat,
    required this.menge,
    this.mhd,
    this.verfaelltInXTagen,
    this.einheit = "g",
    this.anlage,
    this.kategorien = const ["keine"], // 若后续需要修改这个列表,同样要去掉const
    this.kategorienBool = [false], // 去掉const,创建可变列表
    this.offen = false,
    this.color = const Color.fromRGBO(0, 0, 0, 1)
  });

方案2:兼容外部传入的const列表

如果外部调用构造函数时可能传入const列表,可通过初始化列表将所有传入的列表转为可变实例:

Produkt({
    required this.zutat,
    required this.menge,
    this.mhd,
    this.verfaelltInXTagen,
    this.einheit = "g",
    this.anlage,
    List<String>? kategorien,
    List<bool>? kategorienBool,
    this.offen = false,
    this.color = const Color.fromRGBO(0, 0, 0, 1)
  }) : kategorien = List.from(kategorien ?? ["keine"]),
       kategorienBool = List.from(kategorienBool ?? [false]);

这种方式会为每个Produkt实例创建独立的可变列表,彻底避免不可修改的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:46:13