castList method

List? castList(
  1. List list,
  2. Type type, {
  3. bool nullable = false,
})

Cast list to reflectedType if type == reflectedType or return null.

  • If nullable is true casts to a List of nullable values.

Implementation

List? castList(List list, Type type, {bool nullable = false}) {
  if (type == reflectedType) {
    if (nullable) {
      if (list is List<O?>) {
        return list;
      } else {
        return List<O?>.from(list);
      }
    } else {
      if (list is List<O>) {
        return list;
      } else {
        return List<O>.from(list);
      }
    }
  } else if (type == dynamic) {
    return List<dynamic>.from(list);
  } else if (type == Object) {
    return nullable ? List<Object?>.from(list) : List<Object>.from(list);
  }

  var typeInfo = TypeInfo.fromType(type);

  List? callCast<E>() => list.cast<E>();
  List? callCastNullable<E>() => list.cast<E?>();

  var l = nullable
      ? typeInfo.callCasted(callCastNullable)
      : typeInfo.callCasted(callCast);

  return l;
}