Home > Blockchain >  how to convert a List of objects to map
how to convert a List of objects to map

Time:11-24

im tryting to convert a List of objects to map

var mapped;
List<Slots>? data=controller.slots;

mapped = data!.map((e) {
      return {
        DateTime.parse(e.date!): e.slot,
      };
    }).toList();

the output of the variable mapped is

[{2022-11-24 00:00:00.000Z: [Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot']}, {2022-11-25 00:00:00.000Z: [Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot', Instance of 'Slot']}]

and i called this map variable in a function

 List<dynamic> _getEventsfromDay(DateTime date) {
     print(mapped);
    return mapped[date] ?? [];
  }

but it shows me error like

Expected a value of type 'int', but got one of type 'DateTime'

but when i called the mapped variable with index like mapped[0][date] it works

i think it is in iterateable how can i change this to a map varible

CodePudding user response:

You could do something like that:

mapped = Map.fromEntries(
  data!.map((e) => MapEntry(DateTime.parse(e.date!), e.slot),
);

CodePudding user response:

Using the map method, like this:

final sampleData = historical.map((h) => {"open": h.open, "high": h.high, "low": h.low, "close": h.close, "volumeTo": h.volumeTo}).toList();
  • Related