Dart エラー「Error: The value ‘null’ can’t be returned from a function with return type ‘String’ because ‘String’ is not nullable.」が発生した場合の対処法

Dart エラー「Error: The value ‘null’ can’t be returned from a function with return type ‘String’ because ‘String’ is not nullable.」が発生した場合の対処法

Dartで、エラー「Error: The value ‘null’ can’t be returned from a function with return type ‘String’ because ‘String’ is not nullable.」が発生した場合の対処法を記述してます。「firstWhere」の「orElse」で戻り値に「null」を指定した場合に発生します。

環境

  • OS windows11 home
  • Dart 2.18.1

エラー全文

以下のコードを実行時に発生。

void main() {
  var list = ['aaa', 'bbb', 'ccc', 'bbb', 'aaa'];

  print(list.firstWhere((v) => v.startsWith('f'), orElse:() => null));  
}

エラー全文

Error: The value 'null' can't be returned from a function with return type 'String' because 'String' is not nullable.
  print(list.firstWhere((v) => v.startsWith('f'),orElse: () => null));  

原因

「orElse」で「null」は返せないため。

対処法

パッケージ「collection.dart」の「firstWhereOrNull」を使用する

「pubspec.yaml」に以下を追加してインストールします。自分の場合は以下の通りに記述してます。

name: sample
dependencies:
  collection: ^1.17.0
environment:
  sdk: '>=2.10.0 <3.0.0'

「collection 1.17.0」がインストールされます。

[sample] dart pub get
Resolving dependencies...
+ collection 1.17.0
Downloading collection 1.17.0...
Changed 1 dependency!
exit code 0

「firstWhereOrNull」が使用できるようになり「null」が返せるようになります。

import 'package:collection/collection.dart';
void main() {
  var list = ['aaa', 'bbb', 'ccc', 'bbb', 'aaa'];

  print(list.firstWhereOrNull((v) => v.startsWith('f'),)); // null
}