Flutter 如何将返回null的方法转换为“null安全性”
在我以前的项目中,我在dart中使用了一个方法来执行get操作,如果输出无效,我通常会返回null 我的代码-Flutter 如何将返回null的方法转换为“null安全性”,flutter,dart,Flutter,Dart,在我以前的项目中,我在dart中使用了一个方法来执行get操作,如果输出无效,我通常会返回null 我的代码- Future<Map<String, dynamic>> get(String url) async { final response = await http.get( Uri.parse(url), headers: basicHeaderInfo() ); if (response.statusC
Future<Map<String, dynamic>> get(String url) async {
final response = await http.get(
Uri.parse(url),
headers: basicHeaderInfo()
);
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else if (response.statusCode == 401) {
ErrorResponse res = ErrorResponse.fromJson(jsonDecode(response.body));
return null;
} else {
ErrorResponse res = ErrorResponse.fromJson(jsonDecode(response.body));
ToastMessage.error(res.message);
return null;
}
}
我不知道该怎么处理。
在课堂上,还有另一条错误消息
A value of type 'Null' can't be returned from the method 'get' because it has a return type of 'Future<Map<String, dynamic>>'
"The parameter 'errors' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
我就这样解决了-
class ErrorResponse {
String message;
String errors;
ErrorResponse({
this.errors = "",
this.message = "",
});
factory ErrorResponse.fromJson(Map<String, dynamic> json) {
return ErrorResponse(
errors: json["errors"],
message: json["message"],
);
}
}
不知道这是传统还是非传统。在这种情况下,我能想到的最佳选择是
throw Exception;
并在接收代码中使用异常处理try和catch。
另一个选项是返回一个空对象或字符串,然后在代码中进行检查。您应该使用:
Future<Map<String, dynamic>?>
String? message;
String? errors;
阅读以下文章:
我尝试了这种方法,但它导致了另一个问题,当我尝试使用该方法时,如ths=Map mapResponse=WAIT ApiMethod.GetAPIRLS.url1,错误消息flash=cannot assign to the error message清楚地解释了动机,您不能将接受null的值设置为一个不接受null的变量。你读过我上面提到的文章吗?现在就读!是的,我正在使用这种方式,返回{};而不是返回null;问题是,这是一种传统的方法吗?是的,这是一种传统的方法。如果有错误抛出异常,否则只返回空对象。
Future<Map<String, dynamic>?>
String? message;
String? errors;