Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List firstWhere Bad state: No element

Tags:

dart

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);
like image 768
creativecreatorormaybenot Avatar asked Oct 09 '22 23:10

creativecreatorormaybenot


2 Answers

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.

like image 352
creativecreatorormaybenot Avatar answered Oct 12 '22 11:10

creativecreatorormaybenot


Now you can import package:collection and use the extension method firstWhereOrNull

import 'package:collection/collection.dart';

void main() {

  final myList = [1, 2, 3];

  final myElement = myList.firstWhereOrNull((a) => a == 4);

  print(myElement); // null
}
like image 15
Edwin Liu Avatar answered Oct 12 '22 11:10

Edwin Liu