Reputation: 53
There is a Day class and a list of Day objects, I need to convert to a list from map of these objects.
class Day{
double open;
double high;
double low;
double close;
double volumeTo;
Day({this.open, this.high, this.low, this.close, this.volumeTo});
}
List historical = [
new Day(open: 42.6, high: 53.9, low: 39.5, close:56.00, volumeTo: 5000.0),
new Day(open: 42.6, high: 53.9, low: 39.5, close:56.00, volumeTo: 5000.0),
new Day(open: 42.6, high: 53.9, low: 39.5, close:56.00, volumeTo: 5000.0),
new Day(open: 42.6, high: 53.9, low: 39.5, close:56.00, volumeTo: 5000.0),
];
Finally i need for example like this:
List sampleData = [
{"open":42.6, "high":53.9, "low":39.5, "close":56.00, "volumeto":5000.0},
{"open":42.6, "high":53.9, "low":39.5, "close":56.00, "volumeto":5000.0},
{"open":42.6, "high":53.9, "low":39.5, "close":56.00, "volumeto":5000.0},
{"open":42.6, "high":53.9, "low":39.5, "close":56.00, "volumeto":5000.0},
];
Upvotes: 5
Views: 6926
Reputation: 145
If you are using android studio, you can install a pluging to help generate toMap() and fromMap() codes. The name of the plugin is Dart Data Class
After installing the plugin, generate the helper function like this
class Day{
double open;
double high;
double low;
double close;
double volumeTo;
Day({this.open, this.high, this.low, this.close, this.volumeTo});
factory Day.fromMap(Map<String, dynamic> map) {
return new Day(
open: map['open'] as double,
high: map['high'] as double,
low: map['low'] as double,
close: map['close'] as double,
volumeTo: map['volumeTo'] as double,
);
}
Map<String, dynamic> toMap() {
// ignore: unnecessary_cast
return {
'open': this.open,
'high': this.high,
'low': this.low,
'close': this.close,
'volumeTo': this.volumeTo,
} as Map<String, dynamic>;
}
}
// this helper method helps convert to a list of Map
dynamic getListMap(List<dynamic> items) {
if (items == null) {
return null;
}
List<Map<String, dynamic>> dayItems = [];
items.forEach((element) {
dayItems.add(element.toMap());
});
return dayItems;
}
and call the function like this
void somthoing(){
var listOfMap = getListMap(historical);
}
Upvotes: 2
Reputation: 825
Day().historical.map((e)=>{<- do your conversion here ->}).toList();
Upvotes: 2