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)
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)
您应该添加 orElse 以避免异常:
list.firstWhere(
(book) => book.id == id,
orElse: () => null,
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13951 次 |
| 最近记录: |