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
astreats 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
bandarefer to the sameListobject. But then consider:Now you have a situation where
b.lastwould refer to anullelement even thoughbclaims to be aListof non-nullable elements. Just becauseadid not havenullelements at the time you casted it does not mean that it will not havenullelements in the future.What you instead must do is to create a new
Listobject (e.g. withwhereType<T>().toList()) or must create a newList-like object that performs runtime casts for each element (which is whatList.castdoes).