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

How to create object by parsing a Map to constructor?

In Dart, is it possible to create an object by parsing a map to constructor?

Example:

class User {
 final String? id;
 final String? name;
 
 User({this.id, this.name});
}


// Using a map to initiate a `User` object, how to achieve similar functionality?
final map = {'id': '1323', 'name': 'foo'};
User foo = User(map);

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

>Solution :

By creating a factory:

  factory MyUser.fromMap(Map<String, dynamic>? map) {

    if(map == null){
      return MyUser( id: "", nom: "", imageUrl: '');
    }


    return MyUser(
      id: map['id'] as String,
      imageUrl: map['imageUrl'] as String? ?? '',
      nom: map['nom'] as String,
    );
  }
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