Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a List<String?> to List<String> in null safe Dart?

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?

like image 842
Brett Sutton Avatar asked Mar 31 '21 23:03

Brett Sutton


People also ask

How do you use null safety in darts?

Null Safety in simple words means a variable cannot contain a 'null' value unless you initialized with null to that variable. With null safety, all the runtime null-dereference errors will now be shown in compile time. String name = null ; // This means the variable name has a null value.

How do you turn list of objects to list of string in Flutter?

We have 3 steps to convert an Object/List to JSON string: create the class. create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class. get JSON string from JSON object/List using jsonEncode() function.

How to convert a list of int to string in Dart and flutter?

Iterate each element list using the map function. Each element in a string is converted into an int using int.parse This example converts a list of int into a list of String in dart and flutter. List of numbers are iterated using map () Each element in the map is applied with toString () to convert to String.

Can a list ever be null in Dart?

But in null safe Dart, if you have annotated that function with the now non-nullable Listtype, then it knows listwill never be null. That implies the ?.will never do anything useful and you can and should just use ..

What is null safety in Dart programming?

Your Dart program has a whole universe of types in it: primitive types like intand String, collection types like List, and all of the classes and types you and the packages you use define. Before null safety, the static type system allowed the value nullto flow into expressions of any of those types.

Why does Dart promote object to type list instead of object?

In the example here, the then branch of the ifstatement only runs when objectactually contains a list. Therefore, Dart promotes objectto type Listinstead of its declared type Object. This is a handy feature, but it’s pretty limited. Prior to null safety, the following functionally identical program did not work:


2 Answers

  • 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,
    ];
    
  • 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', 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>();
    
like image 144
jamesdlin Avatar answered Oct 10 '22 07:10

jamesdlin


  • Without creating a new List

    void main() {
      List<String?> list = ['a', null, 'b', 'c', null];
      list.removeWhere((e) => e == null); // <-- This is all you need.
      print(list); // [a, b, c]
    }
    
  • Creating a new List

    First create a method, filter for example:

    List<String> filter(List<String?> input) {
      input.removeWhere((e) => e == null);
      return List<String>.from(input);
    }
    

    You can now use it:

    void main() {
      List<String?> list = ['a', null, 'b', 'c', null];
      List<String> filteredList = filter(list); // New list
      print(filteredList); // [a, b, c]
    }
    

To use retainWhere, replace the predicate in removeWhere with (e) => e != null

like image 33
CopsOnRoad Avatar answered Oct 10 '22 06:10

CopsOnRoad