Zvi Karp
Zvi Karp

Reputation: 3904

Dart dynamic class type

I have an abstract class "MyItem" and two classes that extend it, "Item1" and "Item2".

The class "MyItem" is defined MyItem.fromMap(Map<String, dynamic> map); and both that extend it implement the function fromMap.

I'm trying to create a function as follows:

  Future<T> getById<T extends MyItem>(String table, int id) async {
    Map<String, dynamic> item = getItemAsMap(table, id);
    return T.fromMap(item);
  }

But the IDE (VSCode) tells me that I have an error:

The method 'fromMap' isn't defined for the type 'Type'.
Try correcting the name to the name of an existing method, or defining a method named 'fromMap'.

Any insight on what I'm doing wrong?

EDIT Here is the code for the classes:

abstract class MyItem {
  MyItem({
    @required this.name,
  });
  String name;

  MyItem.fromMap(Map<String, dynamic> map);
}

class Item1 extends MyItem {
  Item1({
    this.name,
  }) : super(name: name);
  String name;

  @override
  Item1.fromMap(Map<String, dynamic> map) {
    name = "item 1 name is: ${map['name']}";
  }
}

class Item2 extends MyItem {
  Item2({
    this.name,
    this.address,
  }) : super(name: name);
  String name;
  String address;

  @override
  Item1.fromMap(Map<String, dynamic> map) {
    name = "item 2 name is: ${map['name']}";
    address = map['address'];
  }
}

Upvotes: 0

Views: 976

Answers (1)

BambinoUA
BambinoUA

Reputation: 7100

Dart does not allow generic constructors. T is a generic type. Consider using of factory constructors.

class MyItem {
  factory MyItem(Type type, Map<String, dynamic> map) {
    if (type == Item1) {
      return Item1.fromMap(map);
    } else if (type == Item2) {
      return Item2.fromMap(map);
    }
  }
}

Upvotes: 1

Related Questions