Skip to content

Instantly share code, notes, and snippets.

@dev4jam
Created March 20, 2022 22:15
Show Gist options
  • Save dev4jam/9a29a7e49a084e69fd1d8078d5f2b977 to your computer and use it in GitHub Desktop.
Save dev4jam/9a29a7e49a084e69fd1d8078d5f2b977 to your computer and use it in GitHub Desktop.
Dart inheritance issue
// Model interface
abstract class JsonConvertible {
Map<String, dynamic> toJson();
JsonConvertible.fromJson(Map<String, dynamic> json);
}
// Model
class AccessTokenResponse extends JsonConvertible {
String? accessToken;
@override
Map<String, dynamic> toJson() {
return {};
}
@override
AccessTokenResponse.fromJson(Map<String, dynamic> json)
: super.fromJson(json) {
accessToken = json['access_token'];
}
}
// Network response class
class NetworkResponse<Model> {
Model data;
NetworkResponse.ok(this.data);
}
// Class to create a valid network service request
class NetworkRequest {
}
// Class that performs all network calls
class NetworkService {
Future<NetworkResponse<M>> execute<M extends JsonConvertible>(NetworkRequest request) async {
// For simplicity replaced all DIO calls with static data:
final response = {'data': {'access_token': 'XXX'}};
return NetworkResponse.ok(M.fromJson(response['data'])); //<- Fails here with error: Method 'fromJson' isn't defined for the type 'Type'...
}
}
void main() {
for (int i = 0; i < 5; i++) {
print('hello ${i + 1}');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment