Closed phamconganh closed 8 months ago
The code is only acting on a value
whose run-time type is List<T>
or a subtype thereof (otherwise it proceeds to do return null;
). However, this implies that (1) there are no nulls in the list, or (2) there are nulls in the list, and T
is guaranteed to be a nullable type. This means that there is an inherent loss of information in returning the null free list with the type List<T>
(for example, you'll have to check for null if you take any element from that list and start using it in a way that requires it to be non-null).
You could insist that T
is non-nullable in order to get a better typing of the result:
List<T> safeList<T extends Object>(dynamic value, {List<T> defaultValue = const []}) =>
safeNullableList<T>(value) ?? defaultValue;
List<T>? safeNullableList<T extends Object>(dynamic value) {
if (value is List<T>) return value;
if (value is List<Object?>) return value.whereType<T>().toList();
return null;
}
void showList(List<int> xs) => print(xs);
void main() {
showList(safeList(null, defaultValue: [15]));
showList(safeList([null]));
showList(safeList([1, 2, null, 3]));
}
This looks like an issue for json serializable, please re-open the issue on that repo. I can't transfer it because that is in a different github org.
e.g. I have a nullable list ['text', null] and write a safe conversion