Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to filter null values from map in Dart

Tags:

dart

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 traversing through the whole map and filtering out the values (Traversing whole map and getting Entry Object and discarding those pairs) ?

I need to remove all values that are null and return map

Map<String, dynamic> toMap() {
 return {
  'firstName': this.firstName,
  'lastName': this.lastName
};
like image 642
Yousif khalid Avatar asked May 18 '20 12:05

Yousif khalid


People also ask

How do you remove null values from a List in DART?

We can use contains() function in For Loop to remove empty, null, false, 0 values from a List.

How do you remove null values in flutter?

To remove elements where the id is null, you can use the removeWhere and check if the the current Map with the key id is null. myList. removeWhere((e) => e["id"] == null);

Can map hold null values?

Values entered in a map can be null .


5 Answers

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<dynamic, dynamic> toMap() {
    return <dynamic, dynamic>{
      'firstName': this.firstName,
      'lastName': this.lastName
    }..removeWhere(
            (dynamic key, dynamic value) => key == null || value == null);
  }
}
like image 173
julemand101 Avatar answered Oct 16 '22 12:10

julemand101


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());
}
like image 37
Jorge Wander Santana Ureña Avatar answered Oct 16 '22 12:10

Jorge Wander Santana Ureña


You can now use a map literal with conditional entries:

Map<String, dynamic> toMap() => {
  if (firstName != null) 'firstName': firstName,
  if (lastName != null) 'lastName': lastName,
};

like image 34
lrn Avatar answered Oct 16 '22 12:10

lrn


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);
like image 32
CopsOnRoad Avatar answered Oct 16 '22 11:10

CopsOnRoad


The limitation of removeWhere is that it does not check for nested values. Use this recursive solution if you want to remove all keys in the hierarchy.

  dynamic removeNull(dynamic params) {
    if (params is Map) {
      var _map = {};
      params.forEach((key, value) {
        var _value = removeNull(value);
        if (_value != null) {
          _map[key] = _value;
        }
      });
      // comment this condition if you want empty dictionary
      if (_map.isNotEmpty)
        return _map;
    } else if (params is List) {
      var _list = [];
      for (var val in params) {
        var _value = removeNull(val);
        if (_value != null) {
          _list.add(_value);
        }
      }
      // comment this condition if you want empty list
      if (_list.isNotEmpty)
        return _list;
    } else if (params != null) {
      return params;
    }
    return null;
  }

Example:

  void main() {
    Map<String, dynamic> myMap = {
      "a": 1,
      "b": 2,
      "c": [
        3,
        4,
        null,
        {"d": 7, "e": null, "f": 5}
      ],
      "g": {"h": null, "i": null},
      "j": 6,
      "h": []
    };
    print(removeNull(myMap));
  }

Output:

{a: 1, b: 2, c: [3, 4, {d: 7, f: 5}], j: 6}

Note:

If you want an empty map and list when their child has null values, comment out an empty check for map and list in the code.

like image 22
bikram Avatar answered Oct 16 '22 12:10

bikram