castList method

List castList(
  1. List list, {
  2. bool nullable = false,
})

Casts list to this type (List<T>) if a ClassReflection or EnumReflection for T is registered at ReflectionFactory.

Implementation

List castList(List list, {bool nullable = false}) {
  var mainType = isCollection ? (argumentType(0) ?? TypeInfo.tDynamic) : this;

  if (mainType.isDynamic) {
    return list;
  } else if (mainType.isObject) {
    if (!nullable && list is! List<Object>) {
      return list.cast<Object>();
    }
    return list;
  }

  var reflectionFactory = ReflectionFactory();

  var reflection =
      reflectionFactory.getRegisterClassReflection(mainType.type) ??
          reflectionFactory.getRegisterEnumReflection(mainType.type);

  if (reflection != null) {
    return reflection.castList(list, mainType.type, nullable: nullable) ??
        list;
  }

  if (mainType.isValidGenericType) {
    if (nullable) {
      return mainType.callCasted(<E>() => list.cast<E?>());
    } else {
      return mainType.callCasted(<E>() => list.cast<E>());
    }
  } else {
    return list;
  }
}