列出第一个坏状态:没有元素

问题描述 投票:9回答:1

我正在运行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)

我不明白这意味着什么也无法通过查找at the source来识别问题。

我的firstWhere看起来像这样:

list.firstWhere((element) => a == b);
dart
1个回答
20
投票

当没有匹配元素时会发生这种情况,即当a == b对于list中的任何元素都不为真时,并且未指定可选参数orElse

您还可以指定orElse来处理这种情况:

list.firstWhere((element) => a == b, orElse: () => print('No matching element.'));
© www.soinside.com 2019 - 2024. All rights reserved.