I want to convert my objects to hashmaps so I can use the Flutter method channels to send data to Android.

I've thought of iterating through and mapping them one by one, but there's got to be a more elegant way to do this...



class Something {
  Something(this.what, this.the, this.fiddle);
  final String what;
  final int the;
  final bool fiddle;

Somewhere else

List<Something> listOStuff = List<Something>.generate(10, (int index){
  return Something(index.toString(), index, false,);

List<Map<String, dynamic>> parseToMaps(List<Something> listOStuff){
  List<Map<String, dynamic>> results;
  // do something crazy to get listOStuff into Map of primitive values for each object
  // preferably a built in method of some sort... otherwise, i guess i'll just iterate...
  // maybe even an imported package if such thing exists
  return results;

List<Map<String, dynamic>> listOMaps = parseToMaps(listOStuff);

Something like this in Java

Solution 1: diegoveloper

You can use the map and return the object that you want:

    List<Map<String, dynamic>> listOMaps = listOStuff
            .map((something) => {
                  "what": something.what,
                  "the": something.the,
                  "fiddle": something.fiddle,

Solution 2: rmtmckenzie

I'm not sure what exactly you're looking for, but there is a way to have custom objects encoded without having to specify it directly when you call the method.

What you have to do is implement a MethodCodec and/or MessageCodec that defines how your object is encoded and decoded. The easiest way is probably to subclass StandardMethodCodec and/or StandardMessageCodec (it might be enough to override StandardMessageCodec and pass it to StandardMessageCodec).

If you implement read & write correctly for your object, then all you have to do is pass the list of objects directly to your method call and flutter will handle the encoding.

Note that there are corresponding classes on the Android & iOS sides of things that you could use to have the data decoded directly to objects, and in fact you might have to implement them to get things to work depending on how you do it.