how to filter null values from map in Dart

前端 未结 4 1573
被撕碎了的回忆
被撕碎了的回忆 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:26

    I did this to make it easy remove nulls from map and list using removeWhere: https://dartpad.dartlang.org/52902870f633da8959a39353e96fac25

    Sample:

    
    final data = 
      {
        "name": "Carolina Ratliff",
        "company": null,
        "phone": "+1 (919) 488-2302",
        "tags": [
          "commodo",
          null,
          "dolore",
        ],
        "friends": [
          {
            "id": 0,
            "name": null,
            "favorite_fruits": [
              'apple', null, null, 'pear'
            ]
          },
          {
            "id": 1,
            "name": "Pearl Calhoun"
          },
        ],
      };
    
    void main() {
      // From map
      print('Remove nulls from map:\n' + data.removeNulls().toString());
      // From list
      print('\nRemove nulls from list:\n' + [data].removeNulls().toString());
    }
    
    0 讨论(0)
  • 2021-01-13 10:45

    You can now use a map literal with conditional entries:

    Map<String, dynamic> toMap() => {
      if (firstName != null) 'firstName': firstName,
      if (lastName != null) 'lastName': lastName,
    };
    
    
    0 讨论(0)
  • 2021-01-13 10:52

    I suggest you to use removeWhere function

        Map<String, dynamic> map = {
          '1': 'one',
          '2': null,
          '3': 'three'
        };
    
        map.removeWhere((key, value) => key == null || value == null);
        print(map);
    
    0 讨论(0)
  • 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<String, dynamic> toMap() {
        return <String, dynamic>{
          'firstName': this.firstName,
          'lastName': this.lastName
        }..removeWhere(
            (dynamic key, dynamic value) => key == null || value == null);
      }
    }
    
    
    0 讨论(0)
提交回复
热议问题