我试图将onElse函数添加到itterator.firstWhere方法但我无法正确获得语法.
我尝试过类似的东西
List<String> myList =
String result = myList.firstWhere((o) => o.startsWith('foo'), (o) => null);
Run Code Online (Sandbox Code Playgroud)
但编译器有错误
预期1个位置参数,但发现2个
我确信这是一个简单的语法问题,但它让我难过
Wah*_*hyu 69
万一有人因为谷歌来到这里,搜索null如果firstWhere没有发现如何返回,当您的应用程序为Null Safe 时,使用新方法package:collectioncalled 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');
Run Code Online (Sandbox Code Playgroud)
关于方法:https : //pub.dev/documentation/collection/latest/collection/IterableExtension/firstWhereOrNull.html
Gün*_*uer 27
'orElse'是一个命名的可选参数.
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');
}
}
Run Code Online (Sandbox Code Playgroud)
Dor*_*val 18
使用cast<E?>(),您可以在不添加依赖项的情况下执行此操作:
void main() {
List<String> myList = ["Hello", "World"];
String? result = myList.cast<String?>().firstWhere((o) => o!.startsWith('foo'), orElse: () => null);
print(result ?? "No result");
}
Run Code Online (Sandbox Code Playgroud)
你可以在dartpad上尝试一下。
| 归档时间: |
|
| 查看次数: |
6267 次 |
| 最近记录: |