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
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);
}
}