How to get Map Class index id

11 views
Skip to first unread message

Marc Andrew

unread,
Aug 7, 2018, 4:24:30 PM8/7/18
to Flutter Dev
Hi,

I've been trying to figure how to get the index from my list with map() class.

My List
class MyTestList {
 
MyTestList({this.title});


 
String title;
}
List<MyTestList> myTestList = [
 
MyTestList(title: "Foo 1"),
 
MyTestList(title: "Foo 2"),
 
MyTestList(title: "Foo 3"),
];


I know how to get the value from title key

Map class
myTestList.map((item) {
 
print(item.title);
}).toList();


But how can I get the index?
I would like to have something like this
myTestList.map((item) {
 
print('$index: ${item.title}');
}).toList();

// 0: Foo 1
// 1: Foo 2
// 2: Foo 3


Thank you
Marc

Marc Andrew

unread,
Aug 7, 2018, 4:43:16 PM8/7/18
to Flutter Dev
Hi again,

I believe I figured it out, not sure if this is the best approach though?
Instead of using Map class I'm using List.generate

new List.generate(myTestList.length, (int index){
   
print('$index: ${myTestList[index].title}');
});

Hope someone can help

Thanks

Nitish Kumar Singh

unread,
Aug 7, 2018, 4:45:15 PM8/7/18
to Flutter Dev
class MyTestList {
  
MyTestList({this.title});


  
String title;
}
List<MyTestList> myTestList = [
  
MyTestList(title: "Foo 1"),
  
MyTestList(title: "Foo 2"),
  
MyTestList(title: "Foo 3"),
];

Map<int, String> maps = myTestList.map((item) {
      return item.title;
  }).toList().asMap();
  
  maps.forEach((key,value){
    print('${key} : ${value}');
  });

Marc Andrew

unread,
Aug 7, 2018, 6:31:33 PM8/7/18
to Flutter Dev
Awesome, thank you!
Reply all
Reply to author
Forward
0 new messages