toNonNullList<T> function

List<T> toNonNullList<T>(
  1. List? list, {
  2. bool forceTypeCast = true,
})

Converts list to a List<T> ignoring any null element.

  • forceTypeCast: if true, will try to cast elements as T. if false, will ignore any element that can't be cast.

Implementation

List<T> toNonNullList<T>(List? list, {bool forceTypeCast = true}) {
  if (list == null || list.isEmpty) {
    return <T>[];
  }

  List<T> list2;
  if (forceTypeCast) {
    list2 = list.where((e) => e != null).map((e) => e! as T).toList();
  } else {
    list2 = list.whereType<T>().toList();
  }
  return list2;
}