Home > OS >  How to map a List of Objects in Flutter?
How to map a List of Objects in Flutter?

Time:10-31

I have this List of objects

const List categories = [
  {'title': 'category 1', 'value': 1000},
  {'title': 'category 2', 'value': 2000},
  {'title': 'category 3', 'value': 3000},
];

And I'm trying to map this list to render some UI in a Column widget, so I did this

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  crossAxisAlignment: CrossAxisAlignment.start,
  children: categories.map((e) => Category(title: e.title, value: e.value)).toList(),
),

But it gives me this error enter image description here

CodePudding user response:

Here, I guess you came from javascript, well dart is different a little bit, the elements inside the List are called maps, with Map type, to get a value from that map you need to get it like this :

map["key"]

the keys should be String, so in your case, this will work fine :

`Column(
  mainAxisAlignment: MainAxisAlignment.start,
  crossAxisAlignment: CrossAxisAlignment.start,
  children: categories.map((e) => Category(title: e["title"], value: 
  e["value"])).toList(),
),
  • Related