How to Convert Array List of Object to Map in Flutter

In this post, we are going to show you two methods to convert an array list of objects to a map in Flutter and Dart. If you are converting the list of objects to JSON string, you may need to convert the list of objects to a map first. 

class Student{  //modal class
   String rollno, name, age;
   List<int> marks;

   Student({
     required this.rollno,
     required this.name, 
     required this.age,
     required this.marks
   });
}
List<Student> students = [
    Student(name: "John", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Krishna", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Rahul", rollno: "12", age: "26", marks: [23, 45, 35])
];
     
var studentsmap = students.map((e){
        return {
                "name": e.name, 
                "rollno": e.rollno, 
                "age": e.age, 
                "marks": e.marks
            };
    }).toList();
print(studentsmap);

The output of this code:

[
{name: John, rollno: 12, age: 26, marks: [23, 45, 35]},
{name: Krishna, rollno: 12, age: 26, marks: [23, 45, 35]},
{name: Rahul, rollno: 12, age: 26, marks: [23, 45, 35]}
]

Furthermore, you can convert this list of maps to JSON string using the code below:

import 'dart:convert';
String stringstudents = json.encode(studentsmap);

class Student{
   String rollno, name, age;
   List<int> marks;

   Student({
     required this.rollno,
     required this.name, 
     required this.age,
     required this.marks
   });

   Map<String, dynamic> toMap() {
    return {
      'name': this.name,
      'rollno': this.rollno,
      'age': this.age,
      'marks': this.marks,
    };
  }

  static dynamic getListMap(List<dynamic> items) {
    if (items == null) {
      return null;
    }
    List<Map<String, dynamic>> list = [];
    items.forEach((element) {
      list.add(element.toMap());
    });
    return list;
  }
}
List<Student> students = [
    Student(name: "John", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Krishna", rollno: "12", age: "26", marks: [23, 45, 35]),
    Student(name: "Rahul", rollno: "12", age: "26", marks: [23, 45, 35])
];

var studentsmap1 = Student.getListMap(students);
print(studentsmap1);

The output of this code:

[
{name: John, rollno: 12, age: 26, marks: [23, 45, 35]},
{name: Krishna, rollno: 12, age: 26, marks: [23, 45, 35]},
{name: Rahul, rollno: 12, age: 26, marks: [23, 45, 35]}
]

In this way, you can convert a List of objects to Map in Flutter or Dart.

No any Comments on this Article


Please Wait...