我有一个模型,我希望从HTTP请求中获取响应并将其映射.问题是这个模型有一个可以接受任何属性的属性,但我想正确地映射它.
class BaseResponse<T> {
final bool error;
final String? message;
final T? result;
const BaseResponse({required this.error, this.message, this.result});
factory BaseResponse.fromJson(Map<String, dynamic> json) {
bool error = json['error'];
String? message = json['message'];
T? result = json['result'];
return BaseResponse(error: error, message: message, result: result);
}
}
我想找出一种方法,可以将JSON中的正确数据映射到Result属性中.结果属性可以是复杂的模型,也可以是像String
这样的简单属性.
class SampleModel {
final String firstName;
final String lastName;
final AddressModel address;
SampleModel({ required this.firstName, required this.lastName, required this.address });
}
class AddressModel {
final String street;
final String city;
// ... more properties
AddressModel({ required this.street, required this.city, /* More properties here */ });
}
void main() {
Future<void> getResponse() async {
Future<http.Response> response = await http.get('https://getsomething.com');
// Do some checks against response
BaseResponse<SampleModel> = BaseResponse.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
getResponse();
}