I am trying to write a generic class Repository
which takes a template T
and build T
from a Json (Map<String, dynamic>
). For that I wrote an abstract class:
abstract class JsonSerializable {
String toJson();
JsonSerializable.fromJson(Map<String, dynamic> json);
}
Then I created an item/object class which extends the JsonSerializable
class. This is supposed to be done by any class which is supposed to be passed as a Template in the repository class' methods. The item/object class is:
class Item extends JsonSerializable {
Item.fromJson(super.json) : super.fromJson();
@override
String toJson() {
// TODO: implement toJson
throw UnimplementedError();
}
}
The Repository class which takes the template is as follows:
class Repository<T extends JsonSerializable> {
const Repository();
Future<T> getIdFromJson(Map<String, dynamic> json) async {
return T.fromJson(json)['id'];
}
}
But I am getting the compiler error:
The method 'fromJson' isn't defined for the type 'Type'.
Try correcting the name to the name of an existing method, or defining a method named 'fromJson'.
I also tried to change extends
to implements
in Item
class like:
class Item implements JsonSerializable {
const Item();
@override
factory Item.fromJson(Map<String, dynamic> json) {
return const Item();
}
@override
String toJson() {
throw UnimplementedError();
}
}
But still getting the same error.
What should I change to achieve this functionality. I am relatively new to Dart/Flutter. Please help.