castIterable method

Iterable? castIterable(
  1. Iterable itr,
  2. Type type, {
  3. bool nullable = false,
})

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

  • If nullable is true casts to an Iterable of nullable values.

Implementation

Iterable? castIterable(Iterable itr, Type type, {bool nullable = false}) {
  if (type == reflectedType) {
    if (nullable) {
      if (itr is Iterable<O?>) {
        return itr;
      } else {
        return itr.cast<O?>();
      }
    } else {
      if (itr is Iterable<O>) {
        return itr;
      } else {
        return itr.cast<O>();
      }
    }
  } else if (type == dynamic) {
    return itr.cast<dynamic>();
  } else if (type == Object) {
    return nullable ? itr.cast<Object?>() : itr.cast<Object>();
  }

  var typeInfo = TypeInfo.fromType(type);

  Iterable? callCast<E>() => itr.cast<E>();
  Iterable? callCastNullable<E>() => itr.cast<E>();

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