firstWhere
重新调整根据条件生成的newList
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('green'),
orElse: () => 'No matching color found');
print(newList);
}
输出:
No matching color found
要么
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('blue'),
orElse: () => 'No matching color found');
print(newList);
}
输出:
blue
如果在代码中未定义orElse,并且错误的项目获得了列表中不存在的搜索,则显示BadStateException
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('green'));
print(newList);
}
输出:
Uncaught Error: Bad state: No element
list.firstWhere((element) => a == b, orElse: () => null);
允许您静默返回null。