致所有 Dart 大師:我正在嘗試在 Dart 中實作一個通用網路層,將 REST 服務回應轉換為指定的模型類:
// The idea is to make a network call and get a deserialized model as a response:
final token =
await _authNetworkService.execute<AccessTokenResponse>(request);
這是實作:
// 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'...
}
}
飛鏢墊:https ://dartpad.dev/?id=9a29a7e49a084e69fd1d8078d5f2b977
我怎樣才能達到預期的行為?
uj5u.com熱心網友回復:
解決此問題的一種方法是將fromJson建構式作為引數傳遞給執行函式,但這會在每次呼叫執行時添加另一個步驟
// Class that performs all network calls
class NetworkService {
Future<NetworkResponse<M>> execute<M extends JsonConvertible>(NetworkRequest request,M Function(Map<String, dynamic>) parser ) async {
// For simplicity replaced all DIO calls with static data:
final response = {'data': {'access_token': 'XXX'}};
return NetworkResponse.ok( parser(response['data']!)); //<- Fails here with error: Method 'fromJson' isn't defined for the type 'Type'...
}
}
這就是你呼叫執行函式的方式
final token =
await _authNetworkService.execute<AccessTokenResponse>(request,AccessTokenResponse.fromJson);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/446637.html
上一篇:迭代器在從串列子類化時表現良好,但不是從雙端佇列-Python
下一篇:子類繼承超類并添加屬性
