我正在运行list.firstWhere,这有时会引发异常:
Bad State: No element
When the exception was thrown, this was the stack:
#0 _ListBase&Object&ListMixin.firstWhere (dart:collection/list.dart:148:5)
Run Code Online (Sandbox Code Playgroud)
我不明白这意味着什么也无法通过查看来源来识别问题.
我firstWhere看起来像这样:
list.firstWhere((element) => a == b);
Run Code Online (Sandbox Code Playgroud)
cre*_*not 43
当没有匹配的元素,即当会发生这种情况a == b是从来没有接触过的内容的真实list 和的可选参数orElse没有被指定.
您还可以指定orElse处理这种情况:
list.firstWhere((element) => a == b, orElse: () => print('No matching element.'));
Run Code Online (Sandbox Code Playgroud)
Edw*_*Liu 22
现在您可以导入package:collection并使用扩展方法firstWhereOrNull
import 'package:collection/collection.dart';
void main() {
final myList = [1, 2, 3];
final myElement = myList.firstWhereOrNull((a) => a == 4);
print(myElement); // null
}
Run Code Online (Sandbox Code Playgroud)
firstWhere 返回根据条件生成的 newList
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element == 'green',
orElse: () => 'No matching color found');
print(newList);
}
Run Code Online (Sandbox Code Playgroud)
输出:
No matching color found
Run Code Online (Sandbox Code Playgroud)
或者
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element == 'blue',
orElse: () => 'No matching color found');
print(newList);
}
Run Code Online (Sandbox Code Playgroud)
输出:
blue
Run Code Online (Sandbox Code Playgroud)
如果代码中没有定义 orElse 并且错误的项目得到了列表中不存在的搜索,那么它会显示 BadStateException
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element == 'green');
print(newList);
}
Run Code Online (Sandbox Code Playgroud)
输出:
Uncaught Error: Bad state: No element
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7349 次 |
| 最近记录: |