skip to Main Content

I have a list like List<String?> list1 = ['a', 'b', null, 'c']

How do i get it List<String> list2 = ['a', 'b', 'c']

In Swift I can use compactMap and in Flutter is there any way like compactMap?

4

Answers


  1. List<String?> list1 = ['a', 'b', null, 'c']
    list1.removeWhere((value) => value == null);
    

    or

    List<String?> list1  = ['a', 'b', null, 'c'];
    List<String> list2  = list1.whereType<String>().toList();
    
    Login or Signup to reply.
  2. You can try this short way:

    final List<String> list2 = list1.whereType<String>().toList();
    
    Login or Signup to reply.
  3. Yes, there is an equivalent method in Flutter called whereType() which can be used to filter out null values from a list.

    List<String?> list1 = ['a', 'b', null, 'c'];
    List<String> list2 = list1.whereType<String>().toList();
    print(list2); // ['a', 'b', 'c']
    
    Login or Signup to reply.
  4. You can try like :

    List<String> list2 = list1.nonNulls.toList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search