LoginSignup
7
2

More than 1 year has passed since last update.

[Dart]non-nullable型ListのfirstWhereで検索対象が不在のときにnullを返却したい

Last updated at Posted at 2021-10-17

2021.10.20更新

dart.devが公開しているcollectionパッケージにIterableの拡張メソッドが追加されていたことをコメントでご共有いただいたので、結論に訂正を加えました。
情報をご共有いただいた@Cat_sushiさん、ありがとうございます。


  • 実行環境
    Android Studio Arctic Fox | 2020.3.1 patch 3
    Flutter version 2.5.1
    Dart version 2.14.2

Dart2.12(Flutter2.0)でnull-safetyが導入されてから、List型のfirstWhereで条件にヒットする値が存在しない場合にorElseからnullを返却しようとすると、戻り値の型不一致によりanalyzerに怒られるようになってしまいました。

  final nonNulableList = <String>['a', 'b', 'c', 'd'];
  final result = nonNulableList.firstWhere(
    (elem) => elem == 'e',
    orElse: () => null, // <- 😡
  );
Error: The value 'null' can't be returned from a function with return type 'String' 
because 'String' is not nullable.
    orElse: () => null,
                  ^

現在ではdart.devが公開しているcollectionパッケージにfirstWhereOrNull()という拡張メソッドがあるので、それを使用します。

pubspec.yaml
dependencies:
  collection: ^1.15.0
import 'package:collection/collection.dart';

void main() {
  final nonNullableList = ['a', 'b', 'c', 'd'];
  final result = nonNullableList.firstWhereOrNull(
    (elem) => elem == 'e',
  );
  print('result: $result'); // result: null
}

(以下は古い内容です)

  • 実行環境
    DartPad
    Based on Flutter 2.5.3 Dart SDK 2.14.4

null-safetyな環境でnon-nullable型ListfirstWhereからnullを返却するには、
firstWhereを実行する前にListをnullable型にキャストします。

  final nonNulableList = <String>['a', 'b', 'c', 'd'];
  final result = nonNulableList.cast<String?>().firstWhere( 
   (elem) => elem == 'e',
    orElse: () => null,
  );
  print('result: $result'); // result: null
7
2
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2