Home > Blockchain >  How to print out all key value pairs of an object
How to print out all key value pairs of an object

Time:01-17

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

CodePudding user response:

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}

CodePudding user response:

You can in map like this:

void main() {
  final testMap = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5};
  for (final mapEntry in testMap.entries) {
    final key = mapEntry.key;
    final value = mapEntry.value;
    print('Key: $key, Value: $value');  // Key: a, Value: 1 ...
  }
}

But for your object, you can declare a getter :

class Vehicle {
  String make;
  String model;
  int manufactureYear;
  int vehicleAge;
  String color;

  int get age {
    return vehicleAge;
  }

  void set age(int currentYear) {
    vehicleAge = currentYear - manufactureYear;
  }

  // We can also eliminate the setter and just use a getter.
  //int get age {
  //  return DateTime.now().year - manufactureYear;
  //}

  Vehicle({this.make,this.model,this.manufactureYear,this.color,});
}
  •  Tags:  
  • Related