sdk icon indicating copy to clipboard operation
sdk copied to clipboard

Null safety feedback: How to use firstWhere?

Open xvrh opened this issue 5 years ago • 59 comments

EDIT - best solutions so far:

  • Use package:collection
import 'package:collection/collection.dart';

void main() {
  var list = ['a', 'b', 'c'];
  var d = list.firstWhereOrNull((e) => e == 'd');
}
  • Maintain your own utility extension
extension IterableExtension<T> on Iterable<T> {
  T? firstWhereOrNull(bool Function(T element) test) {
    for (var element in this) {
      if (test(element)) return element;
    }
    return null;
  }
}

void main() {
  var list = ['a', 'b'];
  var d = list.firstWhereOrNull((e) => e == 'd');
}

Original question:

I want to search a list and return null when the element is not found

void main() {
  var list = ['a', 'b', 'c'];

  String? d = list.firstWhere((e) => e == 'd', orElse: () => null);
}

https://nullsafety.dartpad.dev/2d0bc36ec1f3a5ade5550c0944702d73

With null safety, I get this error:

main.dart:4:62: Error: A value of type 'Null' can't be assigned to a variable of type 'String'.
  String? d = list.firstWhere((e) => e == 'd', orElse: () => null);

The orElse parameter of firstWhere is declared not nullable:

E firstWhere(bool test(E element), {E orElse()?})

Why not?

E? firstWhere(bool test(E element), {E? orElse()?})

What is the recommended way to search a collection with null safety enabled?

xvrh avatar Jun 10 '20 21:06 xvrh