Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Failing to convert List<Map<String,dynamic>> into List of Object in Flutter in with fromMap Constructor in flutter

I have created two class named Movie and Person, where person class contains a list of Movie..

I am using toMap method and fromMap Constructor for converting into map to object and visa versa…

But in a Person class i cant understand why following statement not working

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

favmovies:map['favmovies'].map((e)=>Movie.fromMap(e)).toList();

i can solve with some other codes but just want to know where i am wrong in this line.

or suggest me better code

class Movie {
  String? name;
  String? rating;

  Movie({required this.name, required this.rating});

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

  factory Movie.fromMap(Map<String, dynamic> map) {
    return Movie(
      name: map['name'],
      rating: map['age'],
    );
  }
}

class Person {
  String? name;
  String age;
  List<Movie> favmovies;

  Person({required this.age, required this.name, required this.favmovies});

  Map<String, dynamic> toMap() {
    return {
      'name': this.name,
      'age': this.age,
      'favmovies': favmovies.map((e) => e.toMap()).toList(),
    };
  }

  factory Person.fromMap(Map<String, dynamic> map) {
    List<Movie> templist = [];
    for (var x in map['favmovies']) {
      templist.add(Movie.fromMap(x));
    }
    return Person(
        name: map['name'],
        age: map['age'],
      //favmovies:map['favmovies'].map((e)=>Movie.fromMap(e)).toList();

    
    );
  }
}

>Solution :

Try changing it to

favmovies:map['favmovies'].map<Movie>((e)=>Movie.fromMap(e)).toList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading