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

标签 list flutter dart indexof

我想在此列表中获得名称为test 的 ListA的索引
头等舱

class ListA {
  String name;

  ListA({this.name});
}
第二类
List<ListA> abc = [

  ListA(name: 'test'),

];
之后,我得到了一个带有按钮的无状态Wiget,
那就是onPressed方法
onPressed: () {
            i = abc.indexOf(ListA(name: 'test'));
            print(i);
          },
我找不到任何错误,但不幸的是它总是返回-1,这意味着找不到它
我在做什么错?

最佳答案

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

print(ListA(name: 'test') == ListA(name: 'test'));
这将打印false,因为它们不是同一对象。
您可以尝试以下方法之一:
  • 保留对您使用的第一个ListA的引用,并调用indexOf
  • 中传递相同的引用
  • 使用constListA实例(将name字段标记为final,将const添加到构造函数定义及其调用中)
  • 覆盖==类上的 hashCode operator ListA ,因此,如果两个不同的ListA实例的字段/项相同,则认为它们是相同的
  • 代替indexOf,使用indexWhere并检查名称(indexWhere((l) => l.name == 'test'))
  • 关于list - 具有自定义列表的IndexOf(Flutter-Dart),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63535244/

    相关文章:

    flutter - 使连续的按钮在 flutter 中具有相同的宽度

    android-studio - Android Studio IDE : how to debug through my code only in Flutter?

    python - 如何从列表中删除不区分大小写的重复项,同时保持原始列表顺序?

    Python 将列表转换为特定的字典

    python - python 中具有 o(n) 顺序的大列表的快速列表减法

    android - Flutter Container BoxShadow 不显示

    python - 重新格式化列表中的字符串 - Python

    android - VS Code 中没有设备 - Flutter

    flutter - Flutter中的dio软件包是否使用隔离来解码json?

    flutter - Flutter 中 ChangeNotifierProvider 和 ScopedModel 的区别