I have the following models:

  • Author
  • Post
class Author implements Model {
  String name;
  String email;

  User({this.name, this.email});

  factory User.fromMap(Map data) {
    return User(
      name: data['name'] ?? 'Jon Doe'
      email: data['email'] ?? '[email protected]';
    )
  }
}

class Post implements Model {
  User author;
  String content;

  User({this.name, this.email});

  factory Post.fromMap(Map data) {
    return Post(
      author: Author.fromMap(data['author']);
      content: data['content'];
    )
  }
}

My question is, how can I tell dart to "force" all of the models to have a factory Model.fromMap(Map data)?

The reason I want to do so is that I want to fetch these models from an API (JSON).


Solution 1: Nate Bosch

You can not make any requirements around the static shape of a class, because there is nothing you'd be able to accomplish with that information. In order to call Post.fromMap you need to specifically refer to Post.fromMap, you can't call someVariable.fromMap(). There has been some discussion around being able to add requirements to static interfaces, but nothing planned. https://github.com/dart-lang/language/issues/356