Venkat Cpr
Venkat Cpr

Reputation: 163

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

Upvotes: 1

Views: 1151

Answers (2)

Valentin Vignal
Valentin Vignal

Reputation: 8212

You could do something like that:

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

Upvotes: 2

HoRiz
HoRiz

Reputation: 787

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();

Upvotes: 1

Related Questions