how to filter null values from map in Dart

前端 未结 4 1582
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 09:49

Following the map, having both key-value pair as dynamic, Write a logic to filter all the null values from Map without us?

Is there any other approach than traversin

4条回答
  •  悲哀的现实
    2021-01-13 10:53

    Use removeWhere on Map to remove entries you want to filter out:

    void main() {
      final map = {'text': null, 'body': 5, null: 'crap', 'number': 'ten'};
    
      map.removeWhere((key, value) => key == null || value == null);
    
      print(map); // {body: 5, number: ten}
    }
    

    And if you want to do it as part of your toMap() method you can do something like this with the cascade operator:

    void main() {
      print(A(null, 'Jensen').toMap()); // {lastName: Jensen}
    }
    
    class A {
      final String firstName;
      final String lastName;
    
      A(this.firstName, this.lastName);
    
      Map toMap() {
        return {
          'firstName': this.firstName,
          'lastName': this.lastName
        }..removeWhere(
            (dynamic key, dynamic value) => key == null || value == null);
      }
    }
    
    

提交回复
热议问题