Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: How do I convert an array of objects to an array of hashmaps?

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...

Example:

Object

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

like image 709
Johnny Boy Avatar asked Dec 13 '22 13:12

Johnny Boy


1 Answers

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,
                })
            .toList(); 
like image 164
diegoveloper Avatar answered May 15 '23 13:05

diegoveloper