opticon
opticon

Reputation: 3614

Create object from Map - Dart

I have a class with a large number of properties that map to some JSON data I've parsed into a Map object elsewhere. I'd like to be able to instantiate a class by passing in this map:

class Card {
  String name, layout, mana_cost, cmc, type, rarity, text, flavor, artist,
      number, power, toughness, loyalty, watermark, border,
      timeshifted, hand, life, release_date, starter, original_text, original_type,
      source, image_url, set, set_name, id;

  int multiverse_id;

  List<String> colors, names, supertypes, subtypes, types, printings, variations, legalities;
  List<Map> foreign_names, rulings;

  // This doesn't work
  Card.fromMap(Map card) {
    for (var key in card.keys) {
      this[key] = card[key];
    }
  }
}

I'd prefer to not have to assign everything manually. Is there a way to do what I'm trying to do?

Upvotes: 2

Views: 1187

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658253

I don't think there is a good way to do it in the language itself. Reflection would be one approach but it's good practice to avoid it in the browser because it can cause code bloat.

There is the reflectable package that limits the negative size impact of reflection and provides almost the same capabilities.

I'd use the code generation approach, where you use tools like build, source_gen to generate the code that assigns the values.

built_value is a package that uses that approach. This might even work directly for your use case.

Upvotes: 2

Related Questions