Dart リスト(配列)に条件を指定して最初に見つかった値を取得する
Dartで、リスト(配列)に条件を指定して最初に見つかった値を取得するコードを記述してます。「firstWhere」に条件を指定することで取得できます。条件に一致する値がない場合はエラーとなるので「orElse」を使用します。
環境
- OS windows11 home
- Dart 2.18.1
条件を指定して最初に見つかった値を取得
条件を指定して最初に見つかった値を取得するには「 firstWhere 」を使用します。
リスト.firstWhere(条件)実際に、使用して値を取得してみます。
ここでは「startsWith」で、先頭の値が「b」と「c」という2つの条件を指定します。
void main() {
var list = ['apple', 'banana', 'busy', 'arrow', 'cd', 'coffee'];
print(list.firstWhere((v) => v.startsWith('b')));
// banana
print(list.firstWhere((v) => v.startsWith('c')));
// cd
}実行結果を見ると、値が取得されていることが確認できます。

値が存在しない条件を指定するとエラーとなります。
void main() {
var list = ['apple', 'banana', 'busy', 'arrow', 'cd', 'coffee'];
print(list.firstWhere((v) => v.startsWith('e')));
}
Unhandled exception:
Bad state: No element
#0 ListMixin.firstWhere (dart:collection/list.dart:167:5)
#1 main (file:///c:/sample/main.dart:4:14)
#2 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)orElse
「orElse」を指定することで、値が存在しない場合に返す値を指定することが可能です。
void main() {
var list = ['apple', 'banana', 'busy', 'arrow', 'cd', 'coffee'];
print(list.firstWhere((v) => v.startsWith('e'),orElse: () => 'Nothing')); // Nothing
}ただし「null」を指定するとエラーが発生します。
void main() {
var list = ['apple', 'banana', 'busy', 'arrow', 'cd', 'coffee'];
print(list.firstWhere((v) => v.startsWith('e'),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('e'),orElse: () => null)); パッケージ「collection.dart」
「dart.dev」に公開されている「collection.dart」の「firstWhereOrNull」を使用すれば「null」を返すことが可能になります。
最新版はこちらで確認できます。「pubspec.yaml」がなければ作成して以下を追加して使用します。
name: sample
dependencies:
collection: ^1.17.0
environment:
sdk: '>=2.10.0 <3.0.0'実際に使用して「null」を返してみます。
import 'package:collection/collection.dart';
void main() {
var list = ['apple', 'banana', 'busy', 'arrow', 'cd', 'coffee'];
print(list.firstWhereOrNull((v) => v.startsWith('e'),));
// null
print(list.firstWhereOrNull((v) => v.startsWith('b'),));
// banana
}値が存在しない場合は「null」が返っていることが確認できます。
-
前の記事
コマンドプロンプトでファイルの作成日時を変更する方法 2024.08.20
-
次の記事
MariaDB 文字列から文字数を取得する 2024.08.20
コメントを書く