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/posts_page.dart169 行 · 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// 网络请求 UI:`AsyncValue.when` 把 loading / error / data 三态写全。
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'api_exception.dart';
import 'future_builder_page.dart';
import 'post.dart';
import 'providers.dart';
class PostsPage extends ConsumerWidget {
const PostsPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final AsyncValue<List<Post>> posts = ref.watch(postsProvider);
return Scaffold(
appBar: AppBar(
title: const Text('网络请求'),
actions: [
IconButton(
key: const Key('open-future-demo'),
tooltip: 'FutureBuilder 写法',
onPressed: () => Navigator.of(context).push<void>(
MaterialPageRoute<void>(builder: (BuildContext _) => const FutureBuilderPage()),
),
icon: const Icon(Icons.hourglass_empty),
),
IconButton(
key: const Key('refresh'),
tooltip: '刷新',
onPressed: () => ref.read(postsProvider.notifier).refresh(),
icon: const Icon(Icons.refresh),
),
],
),
body: posts.when(
// 1) loading:第一次加载 / 主动 refresh 都会进这里
loading: () => const Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(key: Key('loading-indicator')),
SizedBox(height: 12),
Text('加载中…'),
],
),
),
// 2) error:区分"网络/超时/HTTP/解析",给用户可读文案 + 重试
error: (Object error, StackTrace stack) => _ErrorView(
error: error,
onRetry: () => ref.invalidate(postsProvider), // 重新执行 build() 里的 Future
),
// 3) data
data: (List<Post> items) => RefreshIndicator(
onRefresh: () => ref.read(postsProvider.notifier).refresh(),
child: ListView.separated(
key: const Key('post-list'),
itemCount: items.length,
separatorBuilder: (BuildContext context, int index) => const Divider(height: 1),
itemBuilder: (BuildContext context, int index) {
final Post post = items[index];
return ListTile(
key: Key('post-${post.id}'),
leading: CircleAvatar(child: Text('${post.id}')),
title: Text(post.title, maxLines: 2, overflow: TextOverflow.ellipsis),
subtitle: Text(post.body, maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (BuildContext _) => PostDetailPage(id: post.id),
),
),
);
},
),
),
),
);
}
}
class _ErrorView extends ConsumerWidget {
const _ErrorView({required this.error, required this.onRetry});
final Object error;
final VoidCallback onRetry;
@override
Widget build(BuildContext context, WidgetRef ref) {
final String message = ref.watch(errorMessageProvider(error));
final bool isNetwork = error is NetworkException || error is ApiTimeoutException;
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(isNetwork ? Icons.wifi_off : Icons.error_outline, size: 48),
const SizedBox(height: 12),
Text(message, key: const Key('error-message'), textAlign: TextAlign.center),
const SizedBox(height: 4),
// 调试信息:生产环境应该只上报,不展示细节。
Text(
'$error',
key: const Key('error-detail'),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 16),
FilledButton.icon(
key: const Key('retry'),
onPressed: onRetry,
icon: const Icon(Icons.refresh),
label: const Text('重试'),
),
],
),
),
);
}
}
class PostDetailPage extends ConsumerWidget {
const PostDetailPage({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final AsyncValue<Post> post = ref.watch(postProvider(id));
return Scaffold(
appBar: AppBar(title: Text('文章 #$id')),
body: post.when(
loading: () => const Center(child: CircularProgressIndicator(key: Key('detail-loading'))),
error: (Object error, StackTrace _) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(ref.watch(errorMessageProvider(error)), key: const Key('detail-error')),
const SizedBox(height: 12),
FilledButton(
key: const Key('detail-retry'),
onPressed: () => ref.invalidate(postProvider(id)),
child: const Text('重试'),
),
],
),
),
data: (Post p) => Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(p.title, key: const Key('detail-title'), style: Theme.of(context).textTheme.headlineSmall),
const SizedBox(height: 8),
Text('userId: ${p.userId}'),
const Divider(height: 24),
Text(p.body, key: const Key('detail-body')),
],
),
),
),
);
}
}
代码构成: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 行