asListOrThrow<T> method
Returns the picked value as List. This method throws when value is
not a List
or isAbsent
Each item in the list gets mapped, even when the list contains null
values. To simplify the api, only non-null values get mapped with the
map
function. By default, null
values are ignored. To explicitly
map null
values, use the whenNull
mapping function.
final persons = pick([
{'name': 'John Snow'},
{'name': 'Daenerys Targaryen'},
null, // <-- valid value
]).asListOrThrow(
(pick) => Person.fromPick(pick),
whenNull: (it) => null,
)
// persons
[
Person(name: 'John Snow'),
Person(name: 'Daenerys Targaryen'),
null,
]
For some apis it is important to get the access to the index of an
element in the list. Access it via index which is only available for
list elements, otherwise null
.
Usage:
pick(["John", "Paul", "George", "Ringo"]).asListOrThrow((pick) {
final index = pick.index!;
return Artist(id: index, name: pick.asStringOrThrow());
);
Implementation
List<T> asListOrThrow<T>(
T Function(RequiredPick) map, {
T Function(Pick pick)? whenNull,
}) {
withContext(
requiredPickErrorHintKey,
'Use asListOrEmpty()/asListOrNull() when the value may be null/absent at some point (List<$T>?).',
);
return _parse(map, whenNull: whenNull);
}