List firstWhere Bad state: No element Ask Question

List firstWhere Bad state: No element Ask Question

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.

My firstWhere looks like this:

list.firstWhere((element) => a == b);

ベストアンサー1

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.

You can also specify orElse to handle the situation:

list.firstWhere((a) => a == b, orElse: () => print('No matching element.'));

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 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);

See firstWhereOrNull for more information. Thanks to @EdwinLiu for pointing it out.

おすすめ記事