跳到正文
教程首页
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.dart
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 行
查看全部示例