how to convert a List of objects to map

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

>Solution :

You could do something like that:

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

Leave a Reply