跳到正文
教程首页
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.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')),
            ],
          ),
        ),
      ),
    );
  }
}

代码构成: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 行
查看全部示例