Option A: not working
var a = <Widget?>[Container(), null];
a.removeNulls();
print(a.length == 1 && a[0] != null) // true
var b = a as List<Widget>; // _CastError (type 'List<Widget?>' is not a subtype of type 'List<Widget>' in type cast)
Option B: working
var a = <Widget?>[Container(), null];
a = a.whereType<Widget>().toList();
var b = a as List<Widget>; // works fine
.removeNull() is part of fast_immutable_collections
A cast with
as
treats as object as a different type. It does not mutate the object or create a new object.Suppose that you could cast
List<T?>
asList<T>
for a non-nullable typeT
. For example:now
b
anda
refer to the sameList
object. But then consider:Now you have a situation where
b.last
would refer to anull
element even thoughb
claims to be aList
of non-nullable elements. Just becausea
did not havenull
elements at the time you casted it does not mean that it will not havenull
elements in the future.What you instead must do is to create a new
List
object (e.g. withwhereType<T>().toList()
) or must create a newList
-like object that performs runtime casts for each element (which is whatList.cast
does).