How to convert a List to List in null safe Dart?

  • 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 inserting null elements:

    String? s = maybeNullString();
    var list = <String?>[
      'foo',
      'bar',
      if (someCondition) 'baz',
      if (s != null) s,
    ];
    
  • Dart 3 adds a nonNulls extension to filter out nulls:

    var list = <String?>['foo', 'bar', null, 'baz', null];
    var withoutNulls = list.nonNulls.toList();
    
  • Prior to Dart 3, an easy way to filter out null values from an Iterable<T?> and get an Iterable<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 any null elements but just need to cast the elements to a non-nullable type, other options are to use List.from:

    var list = <String?>['foo', 'bar', 'baz'];
    var withoutNulls = List<String>.from(list);
    

    or if you don’t want to create a new List, Iterable.cast:

    var list = <String?>['foo', 'bar', 'baz'];
    var withoutNulls = list.cast<String>();
    

Leave a Comment