用途:在 Flutter 应用中执行 HTTP 请求并处理 JSON 序列化,用于对接 REST API 或解析外部结构化数据。
核心准则:强制使用 HTTPS(iOS/Android 默认禁用明文 HTTP,调试需要时配置 network_security_config.xml 与 NSAppTransportSecurity);用 Uri.https(authority, unencodedPath, [queryParameters]) 安全构建 URL;始终校验 http.Response.statusCode,将 200、201 视为成功,其他状态码抛出明确异常而非返回 null;解析耗时超过 16ms 的 JSON 用 compute() 移入后台 isolate;对接 LLM 时在系统提示中指定严格 JSON schema 并将响应 MIME 设为 application/json。
HTTP 操作流程:在 pubspec.yaml 添加 http 包;配置平台权限(AndroidManifest.xml 的 Internet 权限、macOS 的 .entitlements);构建 Uri;执行对应方法——GET 用 http.get(uri),POST 用 http.post(uri, headers: {...}, body: jsonEncode(data)) 并确保 Content-Type 为 application/json; charset=UTF-8,PUT 用 http.put,DELETE 用 http.delete;校验状态码,成功时调用 jsonDecode(response.body) 并映射为 Dart 对象。
JSON 序列化:小型原型或简单模型用 dart:convert 手写序列化,需导入 dart:convert、定义含 final 属性的模型类、实现 Model.fromJson 工厂与 toJson;生产级复杂/嵌套模型用 json_serializable 代码生成,命令为 flutter pub add json_annotation 和 flutter pub add -d build_runner json_serializable,模型中导入 json_annotation.dart、添加 part 指令、使用 @JsonSerializable(explicitToJson: true) 注解,再运行 dart run build_runner build --delete-conflicting-outputs。
后台解析大 JSON:创建顶层或静态函数,接收响应体字符串并返回解析后的对象,在其内调用 jsonDecode 并映射到模型;在请求方法中将该函数与 response.body 传给 compute()。
限制:资料未提供除上述以外的性能指标、收费、价格或平台支持范围。