网络请求与 JSON:从 http 到接口封装

使用 http 包发请求,把 JSON 转成模型,并把接口层从页面中拆出来。

网络请求JSON

官方推荐的基础方式

Flutter 官方网络文档中,跨平台 HTTP 请求通常从 http 包开始。它支持 Android、iOS、桌面和 Web。真正项目里也可以使用 Dio 等更强的客户端,但学习阶段先理解请求、响应、JSON 转模型更重要。

class ApiClient {
  final http.Client client;
  ApiClient(this.client);

  Future<Map<String, dynamic>> getJson(Uri uri) async {
    final response = await client.get(uri);
    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw Exception('请求失败:${response.statusCode}');
    }
    return jsonDecode(response.body) as Map<String, dynamic>;
  }
}

模型转换

class UserProfile {
  final int id;
  final String name;

  const UserProfile({required this.id, required this.name});

  factory UserProfile.fromJson(Map<String, dynamic> json) {
    return UserProfile(
      id: json['id'] as int,
      name: json['name'] as String? ?? '未命名',
    );
  }
}

接口封装原则

  • 页面不要直接拼 URL,统一放 service。
  • 统一处理 token、超时、错误码、刷新登录态。
  • 接口返回先转模型,页面不要到处读 Map。
  • 列表接口要约定分页字段,避免页面逻辑混乱。

官方参考