dart-lang / build

A build system for Dart written in Dart
https://pub.dev/packages/build
BSD 3-Clause "New" or "Revised" License
791 stars 211 forks source link

need fromJson with Type #3658

Closed phamconganh closed 8 months ago

phamconganh commented 8 months ago

e.g. I have a nullable list ['text', null] and write a safe conversion

@JsonKey(fromJson: safeList<String>)
List<String> property;
List<T> safeList<T>(dynamic value, {List<T> defaultValue = const []}) => safeNullableList<T>(value) ?? defaultValue;
List<T>? safeNullableList<T>(dynamic value) {
  if (value is List<T>) {
    return value.where((element) => element != null).whereType<T>().toList();
  }
  return null;
}
eernstg commented 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]));
}
jakemac53 commented 8 months ago

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.

https://github.com/google/json_serializable.dart/issues/new