【发布时间】:2021-07-15 06:09:03
【问题描述】:
在我的示例项目中,我使用riverpod 包和freezed 实现了项目。在下面的代码中,我可以成功地从服务器获取数据,但是当我尝试使用model.fromJson 时,我得到了这个错误:
getting type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast
服务器响应数据:
{
"message": "test message",
"statusCode": 1
}
login 模型转换服务器响应的数据和结构:
LoginModel loginModelFromJson(Map<String, dynamic> str) => LoginModel.fromJson(str);
String loginModelToJson(LoginModel data) => json.encode(data.toJson());
@freezed
class LoginModel with _$LoginModel {
const factory LoginModel({
required LoginResponse response,
}) = _LoginModel;
factory LoginModel.fromJson(Map<String, dynamic> json) => _$LoginModelFromJson(json);
}
@freezed
class LoginResponse with _$LoginResponse {
const factory LoginResponse({
required String message,
required int statusCode,
}) = _LoginResponse;
factory LoginResponse.fromJson(Map<String, dynamic> json) => _$LoginResponseFromJson(json);
}
在LoginResponse 类中,我定义了两个参数message 和statusCode,它们由服务器返回。当我尝试使用此请求时,例如:
Future<LoginModel> getResponse(String mobileNumber) async {
const endPoint = 'http://192.168.1.11/api';
try {
final response = await _read(dioProvider).get('${endPoint}/register');
/*GETTING ERROR HERE*/
return loginModelFromJson(response.data as Map<String, dynamic>);
} on DioError catch (e) {
///
}
}
我在getResponse方法的这一行得到了前面提到的错误:
return loginModelFromJson(response.data as Map<String, dynamic>);
【问题讨论】:
标签: flutter dart riverpod flutter-freezed