How to print out all key value pairs of an object
Say I have an object such as:
class Fruit{
String? name;
int? quantity;
String? color;
}
Fruit exampleFruit = Fruit(name: 'Apple', quantity: 3, color: 'red');
What is the most efficient way for me to print out all the key-value pairs?
Pseudo Code I had in mind:
exampleFruit.keys.forEach((key){
Text(key);
}
To clarify, the reason for this question is I have an object where some of the properties can be null. At the moment when displaying these properties, I was wondering if I can make this more efficient by mapping all the existing key-value pairs rather than checking for null and then displaying
Solution 1:
Well, you can create a toJson
method inside your Fruit
class, and always print out your parameters :
class Fruit {
final String? name;
final int? quantity;
final String? color;
const Fruit({
this.color,
this.name,
this.quantity,
});
Map<String, dynamic> toJson() => {
if(name != null) "name": name,
if(quantity != null) "quantity": quantity,
if(color != null) "color": color,
};
}
And then :
Fruit exampleFruit = Fruit(name: 'Apple', quantity: 3, color: 'red');
print(exampleFruit.toJson()); // prints {name: Apple, quantity: 3, color: red}