2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively you could store the Map in a field on this object. The only downside is that you would need to write something like card.props.name instead of just card.name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.