asListOrEmpty<T> method
Returns the picked value as List or an empty list when the value
isn't 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> asListOrEmpty<T>(
T Function(RequiredPick) map, {
T Function(Pick pick)? whenNull,
}) {
if (value == null) return <T>[];
if (value is! List) return <T>[];
return _parse(map, whenNull: whenNull);
}