Home > front end >  How to retrieve data from List<Map<String, dynamic>> model in flutter?
How to retrieve data from List<Map<String, dynamic>> model in flutter?

Time:07-19

let's say I have a model like this ...

class UserModel {
  UserModel({
    required this.data1,
    required this.data2,
    required this.sessions,
  });

  String data1;
  String data2;
  List<Map<String, dynamic>> sessions;
}

and I have variable data like this ...

var userData = [
  UserModel(
    data1: 'Jhon Doe',
    data2: 'Research',
    sessions: [
      {"date": "20 june", "status": "good", "durations": 13},
      {"date": "22 june", "status": "good", "durations": 33},
      {"date": "23 june", "status": "exelent", "durations": 23},
      {"date": "25 june", "status": "good", "durations": 60}
    ],
  ),
  UserModel(
    data1: 'Jean Doe',
    data2: 'Research',
    sessions: [
      {"date": "20 june", "status": "good", "durations": 13},
      {"date": "22 june", "status": "exelent", "durations": 33},
      {"date": "23 june", "status": "exelent", "durations": 23},
      {"date": "25 june", "status": "good", "durations": 60}
    ],
  ),
  UserModel(
    data1: 'Mark Doe',
    data2: 'Resource',
    sessions: [
      {"date": "20 june", "status": "low", "durations": 30},
      {"date": "22 june", "status": "good", "durations": 13},
      {"date": "23 june", "status": "exelent", "durations": 23},
      {"date": "25 june", "status": "good", "durations": 60}
    ],
  ),
];

so, How do I retrieve only all "status" in Map of every User?

I hope you can share the answers, Thanks... cheers

CodePudding user response:

You can use a for each loop

userData.forEach((element){
  element.sessions.forEach(sessionElement){
    print(sessionElement['status']);
  }
});

You can use the same logic in for loop too.

CodePudding user response:

You can use forEach function to iterate through the list

userData.forEach((e){
  e.sessions.forEach(sessionElement){
    print(sessionElement['date']);
    print(sessionElement['status']);
    print(sessionElement['duration']);
  }
});
  • Related