Remove Empty or false Values from a List in Flutter

If you need to remove empty, null, or false values in a List, you may use the code snippets provided in this post to remove them from the list.

The first example uses the built-in List.removeWhere() method to remove all empty, null, or false values from the list. This method takes a predicate as an argument and calls it for each element in the list. If the predicate returns true, the element is removed from the list.

final list = ['', 'Sample','', 100, null, 32, 999999999, false];
list.removeWhere((item) => [null, false, ''].contains(item));
//output: ['Sample', 100, 32, 999999999]

final list = ['', 'Samsung','', 'Apple'];
list.removeWhere((item) => item.isEmpty);
//output: ['Samsung', 'Apple']

The second example uses the built-in List.retainWhere() method to remove all non-empty, non-null, truthy values from the list. This method also takes a predicate as an argument and calls it for each element in the list. If the predicate returns true, the element is retained in the list; if it returns false, the element is removed from the list. These methods can be used to filter out any values you don’t want in your list.

final list = ['', 'Samsung','', 'Apple'];
list.retainWhere((item) => item != '');
//output: ['Samsung', 'Apple']

Or you can use the good old loop approach to remove all the empty, false, and unwanted values from the list.

final list = ['', 'Sample','', 100, null, 32, 999999999, false];
List result = [];

for (var item in list) {
  if (!["", null, false, 0].contains(item)) {
    result.add(car);
  }
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close