我正在尝试制作一个使用“HTTP Get”通信登录 Flutter 的 REST 应用程序。虽然导入“http/http.dart”包并运行 http 类方法没有问题,但我在 Dart/Flutter 中遇到了异常处理问题。我创建了一个调用 http 的方法,但是如果由于任何原因连接中断,它自然会返回一个“SocketException”异常。我在发出 get 请求的同一方法中处理异常没有问题,但是如果我尝试将它在调用方方法堆栈中传递给父方法,我就无法再次捕获它。我找到了“rethrow”关键字,但到目前为止,没有成功重新抛出异常。下面是我在代码中使用的一些方法,包括 login 方法和 caller 方法:
static Future<JsonEnvelop> loginUser(String email, String passwd) async {
List<int> content = Utf8Encoder().convert(passwd);
crypto.Digest digest = crypto.md5.convert(content);
String url = _baseUrl + _loginUrl + email + "/" + digest.toString();
http.Response response;
try {
response = await http.get(url);
} on SocketException catch(e) {
rethrow;
}
if(response != null && response.statusCode == 200) {
return JsonEnvelop.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to login');
}
} …Run Code Online (Sandbox Code Playgroud) 我正在开发使用Flutter开发的移动项目。该项目需要连接到一些用于REST消费服务的服务器(GET,POST,PUT,DELETE等),并检索数据以及向它们发送数据。数据需要使用JSON格式化,因此我决定将Dson的Json序列化库2.0.3与Json批注2.0.0和build_runner 1.2.8结合使用;对于int,String和bool等基本数据类型以及自定义对象,它确实可以正常工作。但它似乎根本不适用于泛型,例如一个<T> item;字段或一个List<T> list;字段。
我的意图是添加一些通用字段,以便可以将它们用于返回所有类型的json类型和结构。我设法找到了第一种情况的解决方案,方法是使用“ @JsonKey”覆盖fromJson和toJson,然后<T>与要在方法中强制转换为的所需类型进行比较。但是,我找不到List<T>类型字段的解决方案。如果我尝试对它们使用批注,那么我得到的只是一个List<dynamic>无用的类型,无法比较用于铸造的类。我该如何解决困境?我应该坚持使用json_serialization还是改用build_value?在这个问题上的任何帮助将不胜感激。
我的代码:
import 'package:json_annotation/json_annotation.dart';
part 'json_generic.g.dart';
@JsonSerializable()
class JsonGeneric<T> {
final int id;
final String uri;
final bool active;
@JsonKey(fromJson: _fromGenericJson, toJson: _toGenericJson)
final T item;
@JsonKey(fromJson: _fromGenericJsonList, toJson: _toGenericJsonList)
final List<T> list;
static const String _exceptionMessage = "Incompatible type used in JsonEnvelop";
JsonGeneric({this.id, this.uri, this.active, this.item, this.list});
factory JsonGeneric.fromJson(Map<String, dynamic> json) =>
_$JsonGenericFromJson(json);
Map<String, dynamic> toJson() => _$JsonGenericToJson(this);
static T _fromGenericJson<T>(Map<String, dynamic> json) { …Run Code Online (Sandbox Code Playgroud)