向 firstWhere 方法添加 orElse 函数

我正在尝试将 onElse 函数添加到 itterator.firstWhere 方法中,但是我无法获得正确的语法。

我尝试过

List<String> myList =


String result = myList.firstWhere((o) => o.startsWith('foo'), (o) => null);

但是编译器有一个错误

预期有1个位置参数,但找到了2个

我确信这是一个简单的语法问题,但它难住了我

65841 次浏览

'orElse' is a named optional argument.

void main() {
checkOrElse(['bar', 'bla']);
checkOrElse(['bar', 'bla', 'foo']);
}


void checkOrElse(List<String> values) {
String result = values.firstWhere((o) => o.startsWith('foo'), orElse: () => '');


if (result != '') {
print('found: $result');
} else {
print('nothing found');
}
}

In case someone came here thanks to google, searching about how to return null if firstWhere found nothing, when your app is Null Safe, use the new method of package:collection called firstWhereOrNull.

import 'package:collection/collection.dart'; // You have to add this manually, for some reason it cannot be added automatically


// somewhere...
MyStuff? stuff = someStuffs.firstWhereOrNull((element) => element.id == 'Cat');

About the method: https://pub.dev/documentation/collection/latest/collection/IterableExtension/firstWhereOrNull.html

void main() {
List<String> myList = ['oof'];


String result = myList.firstWhere((element) =>
element.startsWith('foo'),
orElse: () => 'Found nothing');
print(result);
}

You must add the collections package directly: Run the command below, which will add it to your pubspec.yaml file:

$ flutter pub add collection

ref: collection: ^1.16.0

Using cast<E?>(), you can do this without adding no dependencies:

void main() {
List<String> myList = ["Hello", "World"];


String? result = myList.cast<String?>().firstWhere((o) => o!.startsWith('foo'), orElse: () => null);


print(result ?? "No result");
}

You can try this on dartpad.