简体   繁体   English

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

[英]IndexOf with custom Lists (Flutter - Dart)

I want to get the Index of the ListA with the name test in this list我想在此列表中获取名称为 test 的 ListA的索引

First class第一 class

class ListA {
  String name;

  ListA({this.name});
}

Second class第二个 class

List<ListA> abc = [

  ListA(name: 'test'),

];

after that, i got a statless Wiget with a button, that is the onPressed-method在那之后,我得到了一个带有按钮的无状态 Wiget,那就是 onPressed 方法

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

I couldn´t find any misstakes, but unfortunately it´s always returning -1, what means it couldn´t find it我找不到任何错误,但不幸的是它总是返回-1,这意味着它找不到它

What am i doing wrong?我究竟做错了什么?

This happens because you're creating a new ListA when calling indexOf , and that means you have two different ListA s.发生这种情况是因为您在调用indexOf时创建了一个新的ListA ,这意味着您有两个不同的ListA This is similar to doing:这类似于:

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

This will print false because they're not the same object.这将打印false ,因为它们不是相同的 object。

You could try one of the following:您可以尝试以下操作之一:

  1. Keep a reference to the first ListA you use, and call indexOf passing the same reference in保留对您使用的第一个ListA的引用,并调用indexOf传递相同的引用
  2. Use const instances of ListA (mark the name field as final , add const to the constructor definition and the calls to it)使用ListAconst实例(将name字段标记为final ,将const添加到构造函数定义和对它的调用)
  3. Override the == operator and hashCode on your ListA class, so that the two different instances of ListA are considered the same if their fields/items are the same覆盖ListA class 上的==运算符hashCode ,这样如果ListA的两个不同实例的字段/项目相同,则它们被认为是相同的
  4. Instead of indexOf , use indexWhere and check the name ( indexWhere((l) => l.name == 'test') )而不是indexOf ,使用indexWhere并检查名称( indexWhere((l) => l.name == 'test')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM