示例工程 ch13-network
ch13-network/lib/src/posts_page.dart
// 网络请求 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')),
],
),
),
),
);
}
}