如何在飞镖列表中查找元素

Бог*_*ець 11 dart

我有一个对象的 dart 列表,每个对象都包含book_id属性,我想按book_id字段查找该列表的一个元素。

Kah*_*hou 29

使用 firstWhere 方法:https ://api.flutter.dev/flutter/dart-core/Iterable/firstWhere.html

void main() {
  final list = List<Book>.generate(10, (id) => Book(id));

  Book findBook(int id) => list.firstWhere((book) => book.id == id);

  print(findBook(2).name);  
  print(findBook(4).name);
  print(findBook(6).name);  
}

class Book{
  final int id;

  String get name => "Book$id";

  Book(this.id);
}

/*
Output:
Book2
Book4
Book6
*/
Run Code Online (Sandbox Code Playgroud)

  • 如果请求的项目不在列表中怎么办?它抛出异常! (3认同)

ego*_*ego 18

空安全方法(处理无元素错误)

如果搜索到的项目可能在数组中,也可能不在数组中,那么我个人更喜欢.where在列表中使用空安全性 - 它会过滤数组并返回一个列表。

  var myListFiltered = myList.where((e) => e.id == id);
  if (myListFiltered.length > 0) {
    // Do stuff with myListFiltered.first
  } else {
    // Element is not found
  }
Run Code Online (Sandbox Code Playgroud)

这种方法的好处是你总是会得到一个数组,并且不会出现元素未找到或尝试null通过orElse回调返回的问题:

The return type 'Null' isn't a 'FooBar', as required by the closure's context.
Run Code Online (Sandbox Code Playgroud)

将查找器逻辑重构为辅助方法

由于在对象列表中通过 id 查找元素的任务非常常见,因此我喜欢将该逻辑提取到帮助程序文件中,例如:

class Helpers {
  static findById(list, String id) {
    var findById = (obj) => obj.id == id;
    var result = list.where(findById);
    return result.length > 0 ? result.first : null;
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

var obj = Helpers.findById(myList, id);
if (obj == null) return; //? Exn: element is not found
Run Code Online (Sandbox Code Playgroud)


Ale*_*rov 14

已经说了很多,但我想添加我最好的方法来做到这一点。如果列表中可能不存在该项目,请导入可迭代扩展并firstWhereOrNull1在列表中使用。

import 'package:collection/src/iterable_extensions.dart';

myList.firstWhereOrNull((item) => item.id == id))
Run Code Online (Sandbox Code Playgroud)

  • 我必须导入 `import 'package:collection/collection.dart'` — [来源](/sf/answers/4686952651/)。 (2认同)

Vla*_*kyi 5

您应该添加 orElse 以避免异常:

list.firstWhere(
 (book) => book.id == id,
 orElse: () => null,
);
Run Code Online (Sandbox Code Playgroud)