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

Flutter问题:为何无法用.remove()结合TextFormField移除列表项

问题解决:无法通过名称移除列表中的DayTile对象

问题根源

Dart中默认的对象相等判断是引用相等——只有当两个变量指向内存中同一个对象时,才会被判定为相等。你现在的代码是新建了一个DayTile(title: titleController.text)实例,这个新对象和列表里已有的DayTile实例只是title相同,但不是同一个引用,所以List.remove()找不到要删除的元素。

两种可行解决方案

方案1:直接找到匹配元素删除(推荐)

不用新建对象,通过removeWhere方法遍历列表,根据title匹配删除:

TextButton(
  onPressed: () async {
    setState(() {
      // 匹配时可以加trim()避免空格干扰
      dayTiles.removeWhere((tile) => tile.title.trim() == titleController.text.trim());
    });
    saveData();
    Navigator.pop(context);
  },
  child: const Text("Remove")),

方案2:修改DayTile类的相等判断逻辑

如果需要让DayTile根据title来判断相等,重写类的==运算符和hashCode:

class DayTile {
  final String title;

  DayTile({required this.title});

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is DayTile && other.title == title;
  }

  @override
  int get hashCode => title.hashCode;
}

修改后,你原来的dayTiles.remove(DayTile(title: titleController.text))就能正常工作了。

额外注意点

  • 确认输入的文本和列表中元素的title完全一致,比如大小写、前后空格,必要时用trim()统一处理
  • 如果saveData()是异步操作,建议放在setState之后或者确保状态更新后再保存,避免数据不一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:23:20