Flutter - Iterate through object keys and values

You could also use a getter? It will require you to set up all of the fields once, but after that, you can call the complete list of fields and iterate through that.

class Person{
  final String _firstName;
  final String _secondName;
  Person(this._firstName,this._secondName);

  String get hisName{
    return _firstName;
  }
}


class Player extends Person{

  final int _shirtNumber;

  Player(String _firstName,String _secondName,this._shirtNumber) : super(_firstName, _secondName);

  List get everything{
    final stuff=[_firstName,_secondName,_shirtNumber];

    return stuff;
  }
}


void main(List<String> arguments) {

  final foo = Player('David','Beckham',7);

  print(foo.everything);
  
  for (final blah in foo.everything){
    print(blah);
  }
}

There is not.

What you are asking for is reflection. You can use the dart:mirrors API for that, if the library is available on your platform (it's not in Flutter). You might be able to generate code for it by using package:reflectable. Or you can use package:json_serializable to generate a Map from an object.

If you are just trying to do something for one particular class, I'd just manually write: dart Map<String, dynamic> toJson() => {"id": id, "title": title, "article": article}; and then use that when you want to iterate.


This bugs me almost every day. It's also a problem on the web-side of Dart. In my opinion this is one of the major shortcomings of Dart...

However - here is my solution. I'm using a interface class for these "serializable" classes.

abstract class JsonTO {
    Map<String, dynamic> toJson();
}

class Device implements JsonTO {
    Map<String, dynamic> toJson() {
        return ... Your serialization thing
    }  
}

main() {
    final device = Device();
    final json = device.toJson();

    json.forEach((final String key, final value) {
        _logger.info("Key: {{$key}} -> value: ${value}");
        // do with this info whatever you want
    }); 
}

Tags:

Dart

Flutter