Dercni
Dercni

Reputation: 1224

Create a custom model in dart

I wish to create a custom model that I can reference later: The model is simply a list of countries and their metrics. When the model is created I would like to access it similar to: Countries('au').population

I have created the class below however beyond this I am unsure of how to initialise the model with the data. I believe I need to have a map of Country instances?

class Country {
  final String code;
  final String name;
  final int population;

  Country({
    this.code,
    this.name,
    this.population,
  });

  Map Countries = {'au': new Country('code': 'au', 'name': 'Australia', population: 25000000),
                   'uk': new Country('code': 'uk', 'name': 'United Kingdom', 'population': 66000000)}
}

Upvotes: 2

Views: 550

Answers (2)

Kasandrop
Kasandrop

Reputation: 373

To initialize the model with the data:

Map<String,Country> countries = {'au':Country(code:'au',name:'Australia', population: 25000000),
                                 'uk': Country(code:'uk',name: 'United Kingdom', population: 66000000)};

To access it later and get Australia population:

Country australia=countries['au'];
int populationOfAustralia=australia.population;

Upvotes: 0

Mattia
Mattia

Reputation: 6524

You should use a factory constructor to initialize your class and have all the models in a static method.

class Country {
  final String code;
  final String name;
  final int population;

  Country._({
    this.code,
    this.name,
    this.population,
  });

  factory Country(String code) => countries[code];

  static final countries = {
    'au': Country._(code: 'au', name: 'Australia', population: 25000000),
    'uk': Country._(code: 'uk', name: 'United Kingdom', population: 66000000)
  };
}

then you can do:

var population = Country('au').population; //Returns null if the code is not defined in the map.

Note: your code won't even compile since the parameters names don't need to be defined as string.

Upvotes: 2

Related Questions