带有自定义列表的 IndexOf (Flutter - Dart)

IndexOf with custom Lists (Flutter - Dart)

我想获取此列表中名为 test 的 ListA 的索引

第一个class

class ListA {
  String name;

  ListA({this.name});
}

第二个class

List<ListA> abc = [

  ListA(name: 'test'),

];

在那之后,我得到了一个带按钮的无状态 Wiget, 那就是 onPressed 方法

onPressed: () {
            i = abc.indexOf(ListA(name: 'test'));
            print(i);
          },

我找不到任何错误,但不幸的是它总是返回-1,这意味着它找不到它

我做错了什么?

发生这种情况是因为您在调用 indexOf 时创建了一个新的 ListA,这意味着您有两个不同的 ListA。这类似于做:

print(ListA(name: 'test') == ListA(name: 'test'));

这将打印 false 因为它们不是同一个对象。

您可以尝试以下方法之一:

  1. 保留对您使用的第一个 ListA 的引用,并调用 indexOf
  2. 中传递相同的引用
  3. 使用 ListAconst 个实例(将 name 字段标记为 final,将 const 添加到构造函数定义和对它的调用中)
  4. 覆盖 ListA class 上的 == operator and hashCode,这样 ListA 的两个不同实例如果 fields/items 是一样
  5. 而不是 indexOf,使用 indexWhere 并检查名称 (indexWhere((l) => l.name == 'test'))