Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

abstract class with factory #1027

Closed
tbm98 opened this issue Jun 13, 2020 · 1 comment
Closed

abstract class with factory #1027

tbm98 opened this issue Jun 13, 2020 · 1 comment
Labels
feature Proposed language feature that solves one or more problems state-duplicate This issue or pull request already exists

Comments

@tbm98
Copy link

tbm98 commented Jun 13, 2020

Hi.
I have problem

Future<List<DBParseable>> getAllData(String tableName) async {
    final List<Map<String, dynamic>> maps = await _db.query(tableName);

    switch (tableName) {
      case Schedule.table:
        return List.generate(maps.length, (i) {
          return Schedule.fromJson(maps[i]);
        });
      case Mark.table:
        return List.generate(maps.length, (i) {
          return Mark.fromJson(maps[i]);
        });
      case Profile.table:
        return List.generate(maps.length, (i) {
          return Profile.fromJson(maps[i]);
        });
    }

    return null;
  }

as above function. If I want to parse object by factory .fromJson I can't use generic type because abstract class don't support factory without body.
If abstract class support factory I can do as below

abstract class DBParseable {
  String get tableName;
  Map<String, dynamic> toJson();
  factory fromJson(Map<String,dynamic> json);
}

Future<List<T>> getAllData<T extends DBParseable>(String tableName) async {
    final List<Map<String, dynamic>> maps = await _db.query(tableName);

    return List.generate(maps.length, (i) {
          return T.fromJson(maps[i]);
        });

    return null;
  }
@tbm98 tbm98 added the feature Proposed language feature that solves one or more problems label Jun 13, 2020
@eernstg
Copy link
Member

eernstg commented Jun 13, 2020

This topic may be a duplicate of #356, or at least closely related.

@lrhn lrhn added the state-duplicate This issue or pull request already exists label Jun 20, 2020
@lrhn lrhn closed this as completed Jun 20, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Proposed language feature that solves one or more problems state-duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

3 participants