Skip to content

Commit cf5d523

Browse files
committed
add firstWhere to ListCopyWith
1 parent 6aa7bf2 commit cf5d523

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

packages/dart_mappable/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# 4.6.5
2+
3+
- Added `firstWhere` to `ListCopyWith` for chaining copyWith calls on a list element based on a predicate function.
4+
15
# 4.6.1
26

37
- Record mappers now correctly uses hooks specified on the `@MappableRecord` annotation.

packages/dart_mappable/lib/src/copywith/list_copy_with.dart

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ abstract class ListCopyWith<Result, Elem, Copy> {
2020
/// Access the copyWith interface for the item at [index]
2121
Copy at(int index);
2222

23+
/// Access the copyWith interface for the first item that passes [test]
24+
Copy firstWhere(bool Function(Elem) test);
25+
2326
/// Returns a new list with the item added to the end of the list
2427
Result add(Elem v);
2528

@@ -70,6 +73,15 @@ class _ListCopyWith<Result, Elem, Copy>
7073
@override
7174
Copy at(int index) => _item($value[index], (v) => replace(index, v));
7275

76+
@override
77+
Copy firstWhere(bool Function(Elem) test) {
78+
final index = $value.indexWhere(test);
79+
if (index == -1) {
80+
throw StateError('No element found matching the predicate');
81+
}
82+
return at(index);
83+
}
84+
7385
@override
7486
Result add(Elem v) => addAll([v]);
7587

packages/dart_mappable/pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ dependencies:
2525

2626
dev_dependencies:
2727
build_runner: ^2.4.14
28-
dart_mappable_builder: ^4.6.3
28+
dart_mappable_builder: ^4.6.5
2929
lints: ^5.0.0
3030
test: ^1.25.10
3131

0 commit comments

Comments
 (0)