replaceFirstWhere method Null safety
Replace the first item in the list that satisfies the provided test
with the value
provided or obtained using
the function provided
Searches the list from index start
to the end of the list.
Returns the final value of the item replaced
or null where the test
is not satisfied
var notes = ['do', 're', 'mi', 're'];
var result = notes.replaceFirstWhere(
(note) => note.startsWith('r'),
value: 'la',
);
print(result); // la
result = notes.replaceFirstWhere(
(note) => note.startsWith('r'),
start: 2,
using: (note) => note.replaceFirst('r', 'm'),
);
print(result); // me
result = notes.replaceFirstWhere((note) => note.startsWith('d'));
// throws assertion error
Implementation
T? replaceFirstWhere(bool Function(T) test,
{T? value, T Function(T)? using, int start = 0}) {
final index = indexWhere(test, start);
T? replacement;
if (index != -1) {
replacement = value ?? (using != null ? using(this[index]) : null);
assert(
replacement != null,
'No replacement value provided '
'or calculated using the function supplied',
);
this[index] = replacement!;
}
return replacement;
}