I have a Flutter application (using Dart) where I retrieve data from my Firestore in the form of json.
I have several model classes that I want to convert to and from JSON. Let's say I have the class A
. Serializing is easy because it can be an instance method. However, for deserializing (instantiating A
), there are several ways:
class A {
late String name;
late String email;
A({required this.name, required this.email});
Map<String, dynamic> toJson() {
return {'name': name, 'email': email};
}
// Option 1: Constructor
A.fromJson(Map<String, dynamic> jsonData) {
name = jsonData['name'];
email = jsonData['email'];
}
// Option 2: Factory constructor
factory A.fromJsonFactory(Map<String, dynamic> jsonData) {
return A(name: jsonData['name'], email: jsonData['email']);
}
// Option 3: Static method
static A fromJsonStatic(Map<String, dynamic> jsonData) {
return A(name: jsonData['name'], email: jsonData['email']);
}
}
However, I want to instantiate it from within a generic using the jsonData
:
class Repository<T extends ModelBase> {
void onData(Map<String, dynamic> jsonData) {
// This is just an example
print(T.fromJson(jsonData));
}
}
To that effect, I have attempted the toJson
behavior to be inheritable and declared in a superclass (ModelBase
). I have attempted A
to extend or implement ModelBase
, but seems like I can't get to force the inheritors to implement it, nor can I call it from the generic.
I guess, generalizing, my question is:
- How do I need to define
ModelBase
(which will beT
) ? - What do I need to tell the the generic about
T
?
So that I can instantiate T
(with parameters, not a parameterless constructor) inside the generic of T
in Dart?