I have a list of daily sales which includes "DateTime" & "Int" for each entry.
final data = [
DailySales(2022-03-10 00:00:00.000, 200),
DailySales(2022-03-09 00:00:00.000, 255),
DailySales(2022-02-08 00:00:00.000, 100),
DailySales(2022-02-10 00:00:00.000, 520),
DailySales(2022-01-08 00:00:00.000, 100),
DailySales(2022-01-10 00:00:00.000, 520),
];
class DailySales {
final DateTime day;
final int sales;
DailySales(this.day, this.sales);
}
Now Based on the above list, I need to dynamically generate a new list that shall includes one entry per Month of month name and the total sales for that month.
as shown in the model below:
class MonthlySales {
final String month;
final int sales;
MonthlySales(this.month, this.sales);
}
Can some help on this please
you can do it like this:
main() {
final data = [
DailySales(DateTime.parse("2022-03-10 00:00:00.000"), 200),
DailySales(DateTime.parse("2022-03-09 00:00:00.000"), 255),
DailySales(DateTime.parse("2022-02-08 00:00:00.000"), 100),
DailySales(DateTime.parse("2022-02-10 00:00:00.000"), 520),
DailySales(DateTime.parse("2022-01-08 00:00:00.000"), 100),
DailySales(DateTime.parse("2022-01-10 00:00:00.000"), 520),
];
Map tempMap = Map();
for (DailySales item in data) {
if (tempMap[item.day.month] == null) {
tempMap[item.day.month] = item.sales;
} else {
tempMap[item.day.month] = tempMap[item.day.month] + item.sales;
}
}
List monthlySales = [];
for (int i = 1; i <= 12; i++) {
if (tempMap[i] != null)
monthlySales.add(MonthlySales(i.toString(), tempMap[i]));
}
print(monthlySales);
}
class DailySales {
final DateTime day;
final int sales;
DailySales(this.day, this.sales);
}
class MonthlySales {
final String month;
final int sales;
MonthlySales(this.month, this.sales);
@override
String toString() {
// TODO: implement toString
return "month " + month + " sales " + sales.toString();
}
}
the output would look like:
[month 1 sales 620, month 2 sales 620, month 3 sales 455]