首先列出错误状态:无元素 [英] List firstWhere Bad state: No element
问题描述
我正在运行 list.firstWhere
,有时会抛出异常:
I am running list.firstWhere
and this is sometimes throwing an exception:
Bad State: No element
When the exception was thrown, this was the stack:
#0 _ListBase&Object&ListMixin.firstWhere (dart:collection/list.dart:148:5)
I do not understand what this means an also could not identify the issue by looking at the source.
我的 firstWhere
如下:
list.firstWhere((element) => a == b);
推荐答案
当没有匹配的元素时,即 a == b
对于<未指定code> list 和.
可选参数 orElse
.
This will happen when there is no matching element, i.e. when a == b
is never true for any of the elements in list
and the optional parameter orElse
is not specified.
您还可以指定 orElse
来处理这种情况:
You can also specify orElse
to handle the situation:
list.firstWhere((a) => a == b, orElse: () => print('No matching element.'));
如果要在没有匹配项的情况下返回 null
,也可以使用 orElse
进行此操作:
If you want to return null
instead when there is no match, you can also do that with orElse
:
list.firstWhere((a) => a == b, orElse: () => null);
package:collection
还包含用于的便捷扩展方法> null
情况(在具有null安全性的情况下也应更好地工作):
package:collection
also contains a convenience extension method for the null
case (which should also work better with null safety):
import 'package:collection/collection.dart';
list.firstWhereOrNull((element) => element == other);
请参阅 firstWhereOrNull
更多信息.感谢 @EdwinLiu 指出这一点.
这篇关于首先列出错误状态:无元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!