Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: convert Map to List of Objects

Tags:

flutter

dart

Did several google searches, nothing helpful came up. Been banging my head against some errors when trying to do something that should be pretty simple. Convert a map such as {2019-07-26 15:08:42.889861: 150, 2019-07-27 10:26:28.909330: 182} into a list of objects with the format:

class Weight {   final DateTime date;   final double weight;   bool selected = false;    Weight(this.date, this.weight); } 

I've tried things like: List<Weight> weightData = weights.map((key, value) => Weight(key, value));

There's no toList() method for maps, apparently. So far I'm not loving maps in dart. Nomenclature is confusing between the object type map and the map function. Makes troubleshooting on the internet excruciating.

like image 510
Matt Takao Avatar asked Jul 27 '19 17:07

Matt Takao


People also ask

How do I make a list of objects in Flutter?

To show a list of objects in Flutter we need to take help of several widgets, as well as of the latest Provider package. We can show a list of items on Flutter using many ways. We've already seen how we can use list map() method and list asMap() method to access the list index. for understanding a concept that is fine.

How do you map objects in Dart?

The Map can be declared by using curly braces {} ,and each key-value pair is separated by the commas(,). The value of the key can be accessed by using a square bracket([]).


2 Answers

Following on Richard Heap's comment above, I would:

List<Weight> weightData =   mapData.entries.map( (entry) => Weight(entry.key, entry.value)).toList(); 

Don't forget to call toList, as Dart's map returns a kind of Iterable.

like image 166
ybakos Avatar answered Sep 23 '22 12:09

ybakos


List<Weight> weightData = List();  weights.forEach((k,v) => weightData.add(Weight(k,v)));  
like image 42
Pushan Gupta Avatar answered Sep 19 '22 12:09

Pushan Gupta