0

I have a function with a return type of List<T?>?. I know that I can use the ! operator to convert this return type to List<T?>, but how do I then convert this to a List<T>?

Code that I've tried:

// testFunction returns List<T?>?
var test = testFunction() as List<T>? ?? [];

Result:

The following _CastError was thrown building ...:
type 'List<T?>' is not a subtype of type 'List<T>?' in type cast
  • 1
    You'll have to `map` over the elements and turn each from a `T?` to a `T`. How would you like to handle the nulls? You have three options: 1) force-unwrap and crash (asserting that none of the values should ever be null), 2) substitute a default value with `??`, or 3) `filter` the null elements out and only keep the non-null values. – Alexander Jun 14 '21 at 20:56
  • That worked! Thank you @Alexander - I assumed the answer would be some obscure notation that I hadn't yet stumbled upon. Thankfully not! – pastramislideshow Jun 14 '21 at 21:08

1 Answers1

0

Three solutions

  • This will add and replace null values in a with a default value in b
    List<T?>? a = [];
    List<T>? b = a.map((e) => e ?? defaultValue).toList();

  • These doesn't consider null values
    List<T?>? a = [];
    List<T> b2 = a.filter((v) => v != null).toList();
    List<T?>? a = [];

    List<int>? b2 = [];
    a.forEach((e) {
      if (e != null) b2.add(e);
    });

Sajad Abdollahi
  • 1,593
  • 1
  • 7
  • 19