Rafff
Rafff

Reputation: 1518

How to construct a class with named args from a map?

Let's say I have this class:

class Person {
  final int age;
  final String name;

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

Later then, I want to construct a new instance of this Person class using a data that comes from an external source.

The data are Map<String, dynamic> data

How do I construct a new Person since I can't pass data to the constructor directly because I use named args?

Of course I could do:

final p = Person(age: data['age'], name: data['name']);

But imagine having many many args it would be a pain to do so.

Upvotes: 2

Views: 137

Answers (1)

Miguel Ruivo
Miguel Ruivo

Reputation: 17756

By creating a constructor for that matter:

class Person {
  final int age;
  final String name;

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

   Person.fromMap(Map<String, dynamic> map) : age = map['age'], 
       name = map['name'];
}

You can also assign in the constructor body if you prefer, that makes it more clear if you have more fields.

Upvotes: 1

Related Questions