Issue
I have a dart list:
List<String?> vals;
I want to remove any null values and convert it to a List<String>
.
I’ve tried:
List<String> removeNulls(List<String?> list) {
return list.where((c) => c != null).toList() as List<String>;
}
At run time I’m getting the following error:
List<String?>' is not a subtype of type 'List<String>?'
What is the correct way to resolve this?
Solution
-
Ideally you’d start with a
List<String>
in the first place. If you’re building your list like:String? s = maybeNullString(); var list = <String?>[ 'foo', 'bar', someCondition ? 'baz' : null, s, ];
then you instead can use collection-
if
to avoid insertingnull
elements:String? s = maybeNullString(); var list = <String?>[ 'foo', 'bar', if (someCondition) 'baz', if (s != null) s, ];
-
An easy way to filter out
null
values from anIterable<T?>
and get anIterable<T>
result is to use.whereType<T>()
. For example:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = list.whereType<String>().toList();
-
Another approach is to use collection-
for
with collection-if
:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = <String>[ for (var s in list) if (s != null) s ];
-
Finally, if you already know that your
List
doesn’t contain anynull
elements but just need to cast the elements to a non-nullable type, other options are to useList.from
:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = List<String>.from(list.where((c) => c != null));
or if you don’t want to create a new
List
,Iterable.cast
:var list = <String?>['foo', 'bar', null, 'baz', null]; var withoutNulls = list.where((c) => c != null).cast<String>();
Answered By – jamesdlin
Answer Checked By – David Marino (FlutterFixes Volunteer)