跳到正文
教程首页
FlutterCH 13ch13_network

ch13-network

网络请求:http / dio、超时重试、流式响应、Riverpod 集成。完整工程共 109 个文件,其中 69 个文本源文件可在下面在线阅读。

69

在线文本文件

4,639

源码行数

dart / c / yaml

语言

290 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

textdartxmljsonkotlin

69 text files · 4,639 lines

dartlib/src/api_exception.dart
/// 错误分类:网络层的第一职责是"把底层异常翻译成业务能处理的类型"。
///
/// 对照 Go:`net/http` 返回 `error`,你得自己 `errors.Is(err, context.DeadlineExceeded)`
/// 之类去分类;Dart 用异常,分类即子类。
library;

/// 所有网络/解析错误的基类。
sealed class ApiException implements Exception {
  const ApiException(this.message, {this.cause});

  final String message;
  final Object? cause;

  /// 给用户看的文案(不要把堆栈或英文异常直接丢给用户)。
  String get userMessage => switch (this) {
        NetworkException() => '网络不可用,请检查连接后重试',
        ApiTimeoutException() => '请求超时,请稍后重试',
        RequestCancelledException() => '请求已取消',
        HttpStatusException(:final statusCode) when statusCode == 401 => '登录已过期,请重新登录',
        HttpStatusException(:final statusCode) when statusCode == 404 => '请求的数据不存在',
        HttpStatusException(:final statusCode) when statusCode >= 500 => '服务器开小差了,请稍后重试',
        HttpStatusException() => '请求失败,请稍后重试',
        ParseException() => '数据格式错误,请升级到最新版本',
      };

  @override
  String toString() => '$runtimeType($message)';
}

/// 连不上(DNS 失败、连接被拒、断网)。
class NetworkException extends ApiException {
  const NetworkException(super.message, {super.cause});
}

/// 超时(连接、发送或接收)。
class ApiTimeoutException extends ApiException {
  const ApiTimeoutException(super.message, {super.cause});
}

/// 被主动取消(用户离开页面、点了取消)。
class RequestCancelledException extends ApiException {
  const RequestCancelledException([super.message = '请求已取消']);
}

/// 非 2xx 响应。
class HttpStatusException extends ApiException {
  const HttpStatusException(this.statusCode, this.body)
      : super('HTTP $statusCode');

  final int statusCode;
  final String body;

  bool get isClientError => statusCode >= 400 && statusCode < 500;
  bool get isServerError => statusCode >= 500;

  /// 5xx 和 429(限流)可以重试;4xx 重试没意义。
  bool get isRetryable => isServerError || statusCode == 429;
}

/// 响应能拿到,但不是合法 JSON / 结构不对。
class ParseException extends ApiException {
  const ParseException(super.message, {super.cause});
}

代码构成:text 64 KB · dart 48 KB · xml 41 KB · json 4 KB

本地运行

zip → 解压 → 执行
$cd examples/ch13-network && flutter run -d macos(需要联网;接口是 jsonplaceholder.typicode.com)

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • flutter analyze 0 告警、flutter test 30 个用例全绿(全部用 mock,不依赖真实外网)、flutter build macos --debug 真实构建并启动成功
  • 真实请求 GET /posts?_limit=2 返回 200 / 2 行
查看全部示例