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
darttest/posts_page_test.dart155 行 · 6 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import 'dart:convert';
import 'dart:io';
import 'package:ch13_network/main.dart';
import 'package:ch13_network/src/posts_api.dart';
import 'package:ch13_network/src/providers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
String postsJson(int count) => jsonEncode(<Map<String, Object?>>[
for (var i = 1; i <= count; i++)
<String, Object?>{'id': i, 'userId': 1, 'title': 'title $i', 'body': 'body $i'},
]);
/// 用 MockClient + 零重试延迟的 PostsApi 替换真实网络层。
Widget testApp(MockClient client) => ProviderScope(
overrides: [
postsApiProvider.overrideWith(
(Ref ref) => PostsApi(
client: client,
baseUrl: 'https://example.test',
maxRetries: 0,
retryDelay: Duration.zero,
),
),
],
child: const NetworkApp(),
);
void main() {
testWidgets('loading → data:列表渲染成功', (WidgetTester tester) async {
final MockClient client = MockClient((http.Request request) async {
if (request.url.path == '/posts') return http.Response(postsJson(3), 200);
return http.Response('{}', 404);
});
await tester.pumpWidget(testApp(client));
// 第一帧:loading
expect(find.byKey(const Key('loading-indicator')), findsOneWidget);
await tester.pumpAndSettle();
expect(find.byKey(const Key('post-list')), findsOneWidget);
expect(find.text('title 1'), findsOneWidget);
expect(find.text('title 3'), findsOneWidget);
});
testWidgets('error → 用户可读文案 + 重试成功', (WidgetTester tester) async {
var fail = true;
final MockClient client = MockClient((http.Request request) async {
if (fail) throw const SocketException('Connection refused');
return http.Response(postsJson(1), 200);
});
await tester.pumpWidget(testApp(client));
await tester.pumpAndSettle();
expect(find.byKey(const Key('error-message')), findsOneWidget);
expect(find.text('网络不可用,请检查连接后重试'), findsOneWidget);
// 详情里能看到原始异常(生产环境只上报、不展示)
expect(find.byKey(const Key('error-detail')), findsOneWidget);
fail = false;
await tester.tap(find.byKey(const Key('retry')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('post-list')), findsOneWidget);
expect(find.text('title 1'), findsOneWidget);
});
testWidgets('解析错误也走同一套错误 UI', (WidgetTester tester) async {
final MockClient client = MockClient((http.Request request) async {
return http.Response('<html>bad gateway</html>', 200);
});
await tester.pumpWidget(testApp(client));
await tester.pumpAndSettle();
expect(find.text('数据格式错误,请升级到最新版本'), findsOneWidget);
});
testWidgets('点进详情页:family provider 单独加载', (WidgetTester tester) async {
final List<String> requestedPaths = <String>[];
final MockClient client = MockClient((http.Request request) async {
requestedPaths.add(request.url.path);
if (request.url.path == '/posts') return http.Response(postsJson(2), 200);
return http.Response(
jsonEncode(<String, Object?>{'id': 2, 'userId': 1, 'title': 'detail 2', 'body': 'detail body'}),
200,
);
});
await tester.pumpWidget(testApp(client));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('post-2')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('detail-title')), findsOneWidget);
expect(find.text('detail 2'), findsOneWidget);
expect(requestedPaths, contains('/posts/2'));
});
testWidgets('FutureBuilder 写法:loading → data → 刷新', (WidgetTester tester) async {
final MockClient client = MockClient((http.Request request) async {
// 延迟要大于页面切换动画(~300ms),否则 loading 态会被过渡动画掩盖
await Future<void>.delayed(const Duration(milliseconds: 500));
return http.Response(
jsonEncode(<String, Object?>{'id': 1, 'userId': 1, 'title': 'future title', 'body': 'future body'}),
200,
);
});
await tester.pumpWidget(testApp(client));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('open-future-demo')));
// 不用 pumpAndSettle:loading 里的 CircularProgressIndicator 是无限动画,
// pumpAndSettle 会一路推进到 Future 完成,反而看不到 loading 态。
await tester.pump();
await tester.pump(const Duration(milliseconds: 400)); // 等页面切换动画结束
expect(find.byKey(const Key('future-loading')), findsOneWidget);
await tester.pump(const Duration(milliseconds: 600));
expect(find.text('future title'), findsOneWidget);
// 刷新:setState 换一个新 Future,回到 loading 再回到 data
await tester.tap(find.byKey(const Key('future-reload')));
await tester.pump();
expect(find.byKey(const Key('future-loading')), findsOneWidget);
await tester.pump(const Duration(milliseconds: 600));
expect(find.text('future title'), findsOneWidget);
});
testWidgets('刷新按钮重新请求并保持 data', (WidgetTester tester) async {
var calls = 0;
final MockClient client = MockClient((http.Request request) async {
calls++;
return http.Response(postsJson(1), 200);
});
await tester.pumpWidget(testApp(client));
await tester.pumpAndSettle();
expect(calls, 1);
await tester.tap(find.byKey(const Key('refresh')));
await tester.pumpAndSettle();
expect(calls, 2);
expect(find.byKey(const Key('post-list')), findsOneWidget);
});
}
代码构成: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 行