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/dio_posts_api.dart133 行 · 5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/// 基于 `dio` 的 API 客户端:拦截器、`CancelToken`、`FormData`。
///
/// 为什么还讲 dio?`http` 够简单,但真实项目迟早需要:
/// - 统一拦截(鉴权头、日志脱敏、错误映射、重试)
/// - 取消请求(用户离开页面时取消,省流量也省服务器)
/// - 上传进度 / 下载进度 / 请求去重
/// dio 把这些都做成了内置能力。
library;
import 'dart:async';
import 'package:dio/dio.dart';
import 'api_exception.dart';
import 'post.dart';
class DioPostsApi {
DioPostsApi({Dio? dio, this.baseUrl = 'https://jsonplaceholder.typicode.com'})
: dio = dio ??
Dio(
BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10),
headers: <String, Object?>{'Accept': 'application/json'},
responseType: ResponseType.json,
),
) {
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) {
// 这里只做"记录/上报"。真正的类型映射放在 _asApiException:
// 在拦截器里再包一层 DioException 容易出现"漏掉 response/statusCode"的问题。
handler.next(error);
},
),
);
}
final Dio dio;
final String baseUrl;
/// [cancelToken] 让调用方可以取消请求(离开页面时调用 `cancel()`)。
Future<List<Post>> fetchPosts({int limit = 20, CancelToken? cancelToken}) async {
try {
final Response<List<Object?>> response = await dio.get<List<Object?>>(
'/posts',
queryParameters: <String, Object?>{'_limit': limit},
cancelToken: cancelToken,
);
final List<Object?> data = response.data ?? const <Object?>[];
return <Post>[
for (final Object? raw in data)
if (raw is Map<String, Object?>) Post.fromJson(raw),
];
} on DioException catch (e) {
throw _asApiException(e);
}
}
/// POST JSON。
Future<int> createPost({
required String title,
required String body,
CancelToken? cancelToken,
}) async {
try {
final Response<Map<String, Object?>> response = await dio.post<Map<String, Object?>>(
'/posts',
data: <String, Object?>{'title': title, 'body': body, 'userId': 1},
cancelToken: cancelToken,
);
return (response.data?['id'] as num?)?.toInt() ?? 0;
} on DioException catch (e) {
throw _asApiException(e);
}
}
/// FormData:文件上传(真正发请求时是 multipart/form-data)。
Future<void> uploadBytes({
required List<int> bytes,
required String filename,
void Function(int sent, int total)? onSendProgress,
CancelToken? cancelToken,
}) async {
final FormData form = FormData.fromMap(<String, Object?>{
'file': MultipartFile.fromBytes(bytes, filename: filename),
'note': 'uploaded from ch13 demo',
});
try {
await dio.post<void>(
'/upload',
data: form,
onSendProgress: onSendProgress,
cancelToken: cancelToken,
);
} on DioException catch (e) {
throw _asApiException(e);
}
}
static ApiException _asApiException(DioException e) {
if (e.error is ApiException) return e.error! as ApiException;
switch (e.type) {
case DioExceptionType.cancel:
return const RequestCancelledException();
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
return ApiTimeoutException('请求超时', cause: e);
case DioExceptionType.connectionError:
case DioExceptionType.unknown:
return NetworkException(e.message ?? '网络错误', cause: e);
case DioExceptionType.badResponse:
final int? code = e.response?.statusCode;
if (code == null) return NetworkException('响应异常', cause: e);
return HttpStatusException(code, e.response?.data.toString() ?? '');
case DioExceptionType.badCertificate:
return NetworkException('证书校验失败', cause: e);
case DioExceptionType.transformTimeout:
return const ApiTimeoutException('响应解析超时');
}
}
}
代码构成: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 行