网络请求:http / dio、超时重试、流式响应、Riverpod 集成
第 13 章 · 网络请求:http / dio、超时重试、流式响应、Riverpod 集成
run
$cd examples/ch13-network && flutter run -d macos(需要联网;接口是 jsonplaceholder.typicode.com)已验证
- flutter analyze 0 告警、flutter test 30 个用例全绿(全部用 mock,不依赖真实外网)、flutter build macos --debug 真实构建并启动成功
- 真实请求 GET /posts?_limit=2 返回 200 / 2 行
- 完整工程已打包:打包下载
本章目录 · 20 节
- 13.1 本章目标
- 13.2 http 基础:一个请求的完整形态
- PUT / DELETE
- 编码:永远用 bodyBytes + utf8.decode
- 13.3 错误分类:网络层的第一职责
- 13.4 超时与重试
- 13.5 流式响应与下载进度
- 13.6 dio:拦截器、取消、FormData
- 取消请求
- 表单上传
- 一个实测踩坑:别在拦截器里重复包装异常
- 13.7 与 Riverpod 集成:AsyncValue 三态
- 对照:FutureBuilder(最基础的写法)
- 依赖注入:测试不需要网络
- 13.8 安全与最佳实践
- 13.9 运行与验证
- 两种运行方式
- 静态检查与测试
- 附:C/Go 代码对照:超时 + 分类
- 13.10 本章小结 + C/Go 对照清单
本章与 ch12 是本教程的重点。ch12 解决"字符串 → 模型",本章解决"网络 → 字符串",并把它接到 Riverpod 的三态 UI 上。
13.1 本章目标
- 用
package:http完成 GET/POST、请求头、查询参数、JSON 请求体; - 用分类异常处理错误:网络不通、超时、HTTP 状态码、解析失败,各有各的用户文案;
- 会做超时 + 指数退避重试,并且知道哪些错误不该重试;
- 会读流式响应、做下载进度;
- 会用
dio的拦截器、CancelToken、FormData; - 用 Riverpod 的
AsyncNotifier+AsyncValue.when实现 loading / error / data 三态; - 建立 C/Go 对照:
net/http的client.Do、libcurl 的curl_easy_setopt。
13.2 http 基础:一个请求的完整形态
// examples/ch13-network/lib/src/posts_api.dart
final http.Response response = await client.get(
Uri.parse('$baseUrl/posts?_limit=20'),
headers: <String, String>{'Accept': 'application/json'},
);
| 需求 | package:http 写法 |
Go | C(libcurl) |
|---|---|---|---|
| GET | client.get(uri, headers:) |
http.NewRequest("GET", url, nil) |
CURLOPT_URL |
| POST JSON | client.post(uri, headers:, body: jsonEncode(...)) |
http.NewRequest("POST", url, body) |
CURLOPT_POSTFIELDS |
| 查询参数 | 拼 URL,或用 Uri.parse(...).replace(queryParameters:) |
url.Values.Encode() |
拼字符串 + curl_easy_escape |
| 请求头 | headers: {'Accept': ...} |
req.Header.Set |
CURLOPT_HTTPHEADER |
| 状态码 | response.statusCode |
resp.StatusCode |
CURLINFO_RESPONSE_CODE |
| 响应体 | response.bodyBytes / response.body |
io.ReadAll(resp.Body) |
写回调收到的字节 |
| 释放 | GC | defer resp.Body.Close() |
curl_easy_cleanup |
PUT / DELETE
GET/POST 之外,另外两个方法同样要经过"分类 + 重试"这层:
// examples/ch13-network/lib/src/posts_api.dart
Future<Post> replacePost({required int id, required String title, required String body}) async {
final http.Response response = await _sendWithRetry(
() => client.put(
_uri('/posts/$id'),
headers: <String, String>{...headers, 'Content-Type': 'application/json'},
body: jsonEncode(<String, Object?>{'id': id, 'title': title, 'body': body, 'userId': 1}),
),
);
return Post.fromJson(_decodeBody(response)! as Map<String, Object?>);
}
Future<void> deletePost(int id) async {
await _sendWithRetry(() => client.delete(_uri('/posts/$id'), headers: headers));
}
| 方法 | 幂等 | 重试 | 备注 |
|---|---|---|---|
| GET | ✅ | 安全 | 查询 |
| PUT | ✅ | 安全(整体替换) | 需要完整资源体 |
| DELETE | ✅ | 安全 | 204 通常没有响应体 |
| POST | ❌ | 需幂等键 | 创建,重复提交会产生重复数据 |
编码:永远用 bodyBytes + utf8.decode
Object? _decodeBody(http.Response response) {
try {
// 用 bodyBytes + utf8.decode 而不是 response.body:
// 后者按 Content-Type 猜编码,服务器给错 charset 时会乱码。
return jsonDecode(utf8.decode(response.bodyBytes));
} on FormatException catch (e) {
throw ParseException('响应不是合法 JSON', cause: e);
}
}
测试里专门造了一个"声明 charset=latin1 但内容是 UTF-8 中文"的响应,response.body 会变乱码,utf8.decode(bodyBytes) 正常。这是真实项目里非常常见的坑(尤其是老旧后端和 CDN)。
13.3 错误分类:网络层的第一职责
// examples/ch13-network/lib/src/api_exception.dart
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() => '数据格式错误,请升级到最新版本',
};
}
sealed 保证 switch 穷尽(ch03):新增一种异常,这里会编译失败,逼你写用户文案。
| 异常 | 触发条件 | 用户该做什么 | 自动重试? |
|---|---|---|---|
NetworkException |
DNS 失败、连接被拒、断网 | 检查网络 | ✅ |
ApiTimeoutException |
连接/接收超时 | 稍后重试 | ✅ |
HttpStatusException(5xx) |
服务端错误 | 稍后重试 | ✅ |
HttpStatusException(429) |
限流 | 等更久再试 | ✅ |
HttpStatusException(4xx) |
参数/权限问题 | 修正请求或重新登录 | ❌ |
RequestCancelledException |
用户离开页面 | 无需提示 | ❌ |
ParseException |
JSON 非法/结构不对 | 升级客户端 | ❌ |
为什么分类重要:Go 里你要 errors.Is(err, context.DeadlineExceeded)、os.IsTimeout、检查 *url.Error 层层判断;Dart 里一次 catch + 类型匹配就够,但前提是你在边界层翻译过。不要让 SocketException/DioException 泄漏到 UI。
13.4 超时与重试
Future<http.Response> _sendWithRetry(Future<http.Response> Function() request) async {
var attempt = 0;
while (true) {
try {
final http.Response response = await request().timeout(timeout);
if (response.statusCode < 200 || response.statusCode >= 300) {
final HttpStatusException error = HttpStatusException(response.statusCode, response.body);
if (error.isRetryable && attempt < maxRetries) {
await _backoff(attempt++); // 200ms, 400ms, ...
continue;
}
throw error;
}
return response;
} on ApiException {
rethrow;
} on TimeoutException catch (e) {
if (attempt < maxRetries) { await _backoff(attempt++); continue; }
throw ApiTimeoutException('请求超时(${timeout.inSeconds}s)', cause: e);
} on SocketException catch (e) {
if (attempt < maxRetries) { await _backoff(attempt++); continue; }
throw NetworkException(e.message, cause: e);
} on http.ClientException catch (e) {
if (attempt < maxRetries) { await _backoff(attempt++); continue; }
throw NetworkException(e.message, cause: e);
}
}
}
四条规则:
- 只对可重试错误重试:
5xx/429/ 网络 / 超时。404重试 3 次只是浪费用户流量。 - 指数退避:
retryDelay * 2^attempt,避免雪崩式重试;生产里还应加随机抖动(jitter)。 - 超时是"单次请求"的预算,不是总预算。要限制总耗时,用「整体 deadline」写法(记录开始时间,每次重试前检查剩余预算)。
- 幂等性:GET 天然幂等;POST 重试可能重复下单。要么服务端支持幂等键(
Idempotency-Key),要么客户端不重试 POST。
测试实测的重试次数:
5xx 会重试,最终成功:请求 3 次(1 次 + 2 次重试)
重试用尽:请求 2 次(maxRetries: 1)
404 不重试:请求 1 次
注意:
TimeoutException的 import 来自dart:async,与dart:io的SocketException、package:http的ClientException是三种不同的失败。三个都要接住,否则会以未捕获异常的形式炸到 UI。
13.5 流式响应与下载进度
Future<List<int>> download(
Uri uri, {
void Function(int received, int? total)? onProgress,
int? cancelAfterBytes,
}) async {
final http.StreamedResponse response = await client
.send(http.Request('GET', uri))
.timeout(timeout, onTimeout: () => throw const ApiTimeoutException('下载超时'));
if (response.statusCode < 200 || response.statusCode >= 300) {
throw HttpStatusException(response.statusCode, '');
}
final int? total = response.contentLength;
final List<int> bytes = <int>[];
await for (final List<int> chunk in response.stream) {
bytes.addAll(chunk);
onProgress?.call(bytes.length, total);
if (cancelAfterBytes != null && bytes.length >= cancelAfterBytes) break;
}
return bytes;
}
| 概念 | 说明 | C/Go 类比 |
|---|---|---|
client.send() |
返回 StreamedResponse,头先到、body 是流 |
curl_easy_perform + 写回调 |
response.stream |
Stream<List<int>>,每块到达就触发 |
io.Copy 的 Read 循环 |
contentLength |
总大小(可能为 null) | CURLINFO_CONTENT_LENGTH_DOWNLOAD |
提前 break |
停止消费 = 取消下载 | curl_easy_pause / close(fd) |
不要把整个大文件 await 成一个 List<int>:1GB 文件会 OOM。正确做法是边收边写文件(RandomAccessFile)或边解析。
测试里用自定义的 http.BaseClient(分块返回)验证进度回调:
expect(progress, <String>['6/17', '11/17', '17/17']);
坑:
MockClient只能返回整体响应,测不了进度。必须自己实现BaseClient.send()返回带contentLength的StreamedResponse。
13.6 dio:拦截器、取消、FormData
http 够用,但真实项目很快需要这些能力,dio 内置了:
// examples/ch13-network/lib/src/dio_posts_api.dart
this.dio.interceptors.add(
InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
options.headers['Authorization'] = 'Bearer <token>'; // 统一鉴权
handler.next(options);
},
onResponse: (Response<Object?> response, ResponseInterceptorHandler handler) {
handler.next(response); // 日志/脱敏
},
onError: (DioException error, ErrorInterceptorHandler handler) {
handler.next(error); // 上报
},
),
);
| 能力 | dio 写法 | http 里的做法 |
|---|---|---|
| 拦截器 | interceptors.add(...) |
自己包一层函数 |
| 取消 | CancelToken + token.cancel() |
无内置(要丢结果或中断 stream) |
| 超时 | connectTimeout / receiveTimeout / sendTimeout |
.timeout(...) |
| 上传进度 | onSendProgress |
手写 MultipartRequest |
| 表单 | FormData.fromMap({...MultipartFile...}) |
http.MultipartRequest |
| 重试 | 官方 dio_smart_retry 插件 / 拦截器 |
自己写(本章的 _sendWithRetry) |
取消请求
final CancelToken token = CancelToken();
final Future<List<Post>> request = api.fetchPosts(cancelToken: token);
// 用户离开页面
token.cancel('用户离开了页面');
// request 以 RequestCancelledException 失败
对照 Go:context.WithCancel + http.NewRequestWithContext。这是用户离开页面时必须做的事:不取消的话请求继续跑、回调继续持有 State(ch06 的泄漏模式)。
表单上传
final FormData form = FormData.fromMap(<String, Object?>{
'file': MultipartFile.fromBytes(bytes, filename: filename),
'note': 'uploaded from ch13 demo',
});
await dio.post<void>('/upload', data: form, onSendProgress: (sent, total) { ... });
一个实测踩坑:别在拦截器里重复包装异常
最初 onError 里把 DioException 重新包装成"错误已映射"的版本,结果 404 变成了 NetworkException——因为新构造的对象丢了 response,后续分类只能落到"未知类型"。
结论:onError 只做记录/上报,类型映射放到每个请求方法的 catch 里(或用一个专门的最外层 wrapper),保证 DioExceptionType 与 response.statusCode 都还完整。
13.7 与 Riverpod 集成:AsyncValue 三态
// examples/ch13-network/lib/src/providers.dart
final postsApiProvider = Provider<PostsApi>(
(Ref ref) => PostsApi(client: ref.watch(httpClientProvider)),
);
class PostsNotifier extends AsyncNotifier<List<Post>> {
@override
Future<List<Post>> build() => ref.watch(postsApiProvider).fetchPosts();
Future<void> refresh() async {
state = const AsyncLoading<List<Post>>();
state = await AsyncValue.guard<List<Post>>(
() => ref.read(postsApiProvider).fetchPosts(),
);
}
}
final postsProvider = AsyncNotifierProvider<PostsNotifier, List<Post>>(PostsNotifier.new);
// examples/ch13-network/lib/src/posts_page.dart
final AsyncValue<List<Post>> posts = ref.watch(postsProvider);
posts.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (Object error, StackTrace stack) => _ErrorView(error: error, onRetry: () => ref.invalidate(postsProvider)),
data: (List<Post> items) => ListView.separated(...),
);
三个要点:
build()返回Future→ 自动变成AsyncValue,不用手写isLoading/error/data三个字段。AsyncValue.guard把try/catch变成"值":成功是AsyncData,失败是AsyncError。UI 不用 try/catch。ref.invalidate让 provider 重新执行build()(回到 loading 再加载);refresh()则是手动控制"先 loading 再加载"。
对比 FutureBuilder(ch02 提过):
FutureBuilder |
Riverpod AsyncValue |
|
|---|---|---|
| 状态来源 | 每次 build 都新建 Future(容易重复请求) | provider 缓存,跨 widget 共享 |
| 错误处理 | 要自己转换异常 | AsyncError + errorMessageProvider |
| 重试 | 手动 setState 换 Future |
ref.invalidate |
| 跨页面 | 不共享 | 共享 |
对照:FutureBuilder(最基础的写法)
Riverpod 不是唯一选择。第三方代码里最常见的写法是 FutureBuilder:
// examples/ch13-network/lib/src/future_builder_page.dart
class _FutureBuilderPageState extends ConsumerState<FutureBuilderPage> {
late Future<Post> _future;
@override
void initState() {
super.initState();
// ★ Future 只能在 initState 创建;放进 build 会每次重建都重新请求
_future = ref.read(postsApiProvider).fetchPost(1);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Post>(
future: _future,
builder: (BuildContext context, AsyncSnapshot<Post> snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) return Text('${snapshot.error}');
return Text(snapshot.data!.title);
},
);
}
}
两者对比:
FutureBuilder |
Riverpod AsyncValue |
|
|---|---|---|
| Future 存放 | State 字段,手动 setState 换新 |
provider 内部缓存 |
| 跨页面共享 | ❌ | ✅ |
| 重试 | setState(() => _future = ...) |
ref.invalidate |
| 三态 | connectionState + hasError + data |
loading/error/data |
| 常见 bug | 在 build 里创建 Future |
在 build 里发请求 |
示例 AppBar 上的沙漏图标可以打开这个页面,测试覆盖了 loading → data → 刷新的完整过程。
依赖注入:测试不需要网络
// test/posts_page_test.dart
Widget testApp(MockClient client) => ProviderScope(
overrides: [
postsApiProvider.overrideWith(
(Ref ref) => PostsApi(client: client, baseUrl: 'https://example.test', maxRetries: 0),
),
],
child: const NetworkApp(),
);
http.MockClient 让我们能精确模拟:200 正常、500 三次后成功、404、连不上、超时、非法 JSON、字段类型错误。所有测试都不碰外网(AGENTS.md §10.3 的硬要求)。
13.8 安全与最佳实践
| 项 | 做法 | 反例 |
|---|---|---|
| 传输 | 只允许 HTTPS;证书校验默认开启(dio 的 badCertificateCallback 别乱返回 true) |
明文 HTTP 传 token |
| 鉴权 | token 从安全存储读(Android Keystore / iOS Keychain / 桌面 keyring),运行时注入请求头 | 写死在代码里、放 assets |
| 日志 | 只记方法/URL/状态码/耗时;header 与 body 脱敏 | 把 Authorization 打进日志 |
| 错误提示 | 用分类后的 userMessage |
把堆栈丢给用户 |
| 取消 | 页面 dispose 时取消进行中的请求 |
离开页面后回调仍 setState |
| 重试 | 只重试幂等请求;POST 需要幂等键 | 无脑重试 POST 导致重复下单 |
| 缓存 | 列表加 ETag/If-None-Match;图片用 cached_network_image |
每次进页面全量拉取 |
13.9 运行与验证
两种运行方式
方式 A:真实公共接口(默认,需要联网)
cd examples/ch13-network
flutter pub get
flutter run -d macos # 默认 baseUrl = https://jsonplaceholder.typicode.com
方式 B:本地 mock 服务器(完全离线,CI/飞机上都能跑)
# 终端 1:启动 mock(dart:io HttpServer,无第三方依赖)
dart run bin/mock_server.dart 8080
# 终端 2:把接口地址指过去
flutter run -d macos --dart-define=POSTS_API=http://127.0.0.1:8080
mock 服务器实现了 GET /posts?_limit=N 与 GET /posts/:id,返回中文假数据:
$ curl "http://127.0.0.1:8080/posts?_limit=2"
[{"id":1,"userId":1,"title":"本地 mock 文章 1",...},{"id":2,...}]
接口地址通过 String.fromEnvironment 注入,代码里没有环境分支:
// examples/ch13-network/lib/src/providers.dart
const String _baseUrl = String.fromEnvironment(
'POSTS_API',
defaultValue: 'https://jsonplaceholder.typicode.com',
);
静态检查与测试
flutter analyze # No issues found!
flutter test # All tests passed! (30 个用例,全部 mock,不依赖上面两种方式)
flutter build macos --debug
真实网络验证(示例之外的一次直接请求):
status=200 rows=2 first=sunt aut facere repellat provident occaecati excepturi optio reprehenderit
本次构建与启动:
✓ Built build/macos/Build/Products/Debug/ch13_network.app
flutter: The Dart VM service is listening on http://127.0.0.1:61789/...
附:C/Go 代码对照:超时 + 分类
// Go:context 控制超时,错误用 errors.Is 分类
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, ErrTimeout // 超时
}
return nil, ErrNetwork // 连不上
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
// 5xx:可重试(自己实现退避)
}
body, err := io.ReadAll(resp.Body)
// Dart:异常即分类,catch 一次搞定
try {
final response = await client.get(uri).timeout(const Duration(seconds: 10));
if (response.statusCode >= 500) throw HttpStatusException(response.statusCode, response.body);
return jsonDecode(utf8.decode(response.bodyBytes));
} on TimeoutException {
throw const ApiTimeoutException('请求超时'); // 分类 1
} on SocketException {
throw NetworkException('网络不可用'); // 分类 2
} on FormatException {
throw const ParseException('响应不是合法 JSON'); // 分类 3
}
Go 的错误是"返回值 + 手动分类",Dart 的错误是"异常 + 类型匹配"。前者不可漏检,后者写起来短,但必须在边界层翻译,否则 SocketException 会一路冒到 UI。
13.10 本章小结 + C/Go 对照清单
| 主题 | Go | C(libcurl) | Dart | 陷阱 |
|---|---|---|---|---|
| 发请求 | client.Do(req) |
curl_easy_perform |
client.get/post / dio.get |
忘记查状态码 |
| 超时 | client.Timeout / context |
CURLOPT_TIMEOUT |
.timeout(...) / connectTimeout |
只设了连接超时,没设接收超时 |
| 取消 | context.WithCancel |
curl_easy_pause |
CancelToken / 停止消费 stream |
页面销毁后回调还在跑 |
| 错误分类 | errors.Is + 多态判断 |
返回码 + curl_easy_strerror |
sealed ApiException + switch |
让底层异常泄漏到 UI |
| 重试 | 自己写 / 中间件 | 自己写 | 自己写(dio 插件) | 重试 4xx / 非幂等 POST |
| 响应解析 | json.Unmarshal |
cJSON_Parse |
jsonDecode(utf8.decode(bodyBytes)) |
信了错误的 charset |
| 流式下载 | io.Copy |
写回调 | StreamedResponse.stream |
一次读进内存 → OOM |
| 并发请求 | goroutine + errgroup |
多 handle | Future.wait |
串行 await 变慢 |
| 状态集成 | 手写 loading/error 字段 | — | AsyncValue 三态 |
在 build 里发请求 |
给 C/Go 老兵的三句话:
- 网络层只做三件事:发请求、翻译错误、解析数据。把这三件事放在一起写,是后期最难维护的代码。
- 超时、取消、重试都必须显式设计;
await不会自动帮你做任何一件。 - 测试必须 mock 到"字节"这一层(
MockClient),否则你的 CI 迟早会因为外网抖动变红。
下一章进入交付阶段:本地持久化(shared_preferences、drift/SQLite),把本章拿到的数据真正存下来。