← Flutter / Dart

Flutter / Dart · 20 / 24

REST with cancellation and pagination

Load pages from a local HTTP server and cancel a pending request.

  • Large
  • Advanced
  • 90 min

Prerequisites: Null safety, errors and Future, Clean MVVM, services and repositories

In this tutorial
  1. Define the boundary
  2. Set up the learning project
  3. Trace the successful outcome
  4. Observe failures deliberately
  5. Solve the extension
  6. Compare the solution
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

Flutter 3.41.5 or newer with Dart 3.11. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

This HttpClient example needs a native Dart target. It does not run unchanged on the web.

Verified on 2026-10-20 on Linux x86_64. A local HTTP server returns real JSON responses. Tests cover pages, invalid responses and cancellation. A browser requires a compatible web transport instead.

Awaiting a Future does not cancel an older network request. This native Dart client owns one HttpClient per request and can close it explicitly. The server returns a cursor for the next page. Tests use a real local HttpServer and a deliberately delayed response. This dart:io example targets native platforms.

Package contents and individual files

01Define the boundary

The page number belongs to both request and result. The parser validates the response shape before accepting it. A dedicated HttpClient per operation allows cancellation through close. This dart:io implementation targets native Flutter platforms.

lib/model.dart · dartOpen file
import 'dart:convert';
import 'dart:io';

class PageResult {
  PageResult(this.items, this.next);
  final List<String> items;
  final int? next;
}

class Cancelled implements Exception {}

class PageRequest {
  final HttpClient _client = HttpClient();
  bool _cancelled = false;
  void cancel() {
    _cancelled = true;
    _client.close(force: true);
  }

  Future<PageResult> load(Uri uri) async {
    if (_cancelled) throw Cancelled();
    try {
      final response = await (await _client.getUrl(uri)).close();
      if (response.statusCode != 200)
        throw HttpException('HTTP ${response.statusCode}');
      final data = jsonDecode(await utf8.decoder.bind(response).join());
      if (data is! Map<String, dynamic> ||
          data['items'] is! List ||
          !(data['items'] as List).every((x) => x is String) ||
          (data['next'] != null && data['next'] is! int)) {
        throw const FormatException('Invalid page');
      }
      if (_cancelled) throw Cancelled();
      return PageResult(
        List<String>.from(data['items'] as List),
        data['next'] as int?,
      );
    } catch (_) {
      if (_cancelled) throw Cancelled();
      rethrow;
    } finally {
      _client.close(force: true);
    }
  }
}

02Set up the learning project

Direct dependencies are pinned. Extract all files together and run flutter pub get. Do not use an existing app database for tests. Tests create and clean up their own data.

pubspec.yaml · yamlOpen file
name: learning_example
publish_to: none
environment:
  sdk: ">=3.11.0 <4.0.0"
dependencies:
  flutter:
    sdk: flutter
  flutter_riverpod: 3.3.1
  drift: 2.33.0
  path_provider: 2.1.5
dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:
  uses-material-design: true

03Trace the successful outcome

A local HTTP server returns real JSON responses. Tests cover pages, invalid responses and cancellation. A browser requires a compatible web transport instead.

test/model_test.dart · dartOpen file
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:learning_example/model.dart';

void main() {
  test(
    'two pages, invalid JSON and cancellation use a real HTTP boundary',
    () async {
      final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
      addTearDown(() => server.close(force: true));
      final waiting = Completer<void>();
      server.listen((request) async {
        if (request.uri.path == '/slow') {
          waiting.complete();
          return;
        }
        request.response.headers.contentType = ContentType.json;
        request.response.write(
          request.uri.path == '/bad'
              ? '{"items":[12]}'
              : request.uri.queryParameters['page'] == '2'
              ? '{"items":["B"],"next":null}'
              : '{"items":["A"],"next":2}',
        );
        await request.response.close();
      });
      final base = Uri.parse('http://127.0.0.1:${server.port}');
      final first = await PageRequest().load(base);
      final second = await PageRequest().load(
        base.replace(queryParameters: {'page': '${first.next}'}),
      );
      expect([...first.items, ...second.items], ['A', 'B']);
      expect(second.next, isNull);
      await expectLater(
        PageRequest().load(base.resolve('/bad')),
        throwsFormatException,
      );
      final request = PageRequest();
      final done = expectLater(
        request.load(base.resolve('/slow')),
        throwsA(isA<Cancelled>()),
      );
      await waiting.future.timeout(const Duration(seconds: 3));
      request.cancel();
      await done;
    },
  );
}

Run / check

flutter pub get
flutter test
Expected result

A local HTTP server returns real JSON responses. Tests cover pages, invalid responses and cancellation. A browser requires a compatible web transport instead.

04Observe failures deliberately

Change an expected number or state in the test. flutter test must fail. Restore the correct expectation afterwards. Distinguish a domain failure from a missing plugin or development environment.

05Solve the extension

Also verify cancellation before a request starts.

06Compare the solution

After cancel, load must not start a network request. The additional test expects the same domain cancellation type. An interface should additionally reject stale responses by request identity.

Expected result

flutter test passes for the original example and the extended solution.

Your exercise

Also verify cancellation before a request starts.

Show the solution and explanation

After cancel, load must not start a network request. The additional test expects the same domain cancellation type. An interface should additionally reject stale responses by request identity.

solution/model_test.dart · dartOpen file
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:learning_example/model.dart';

void main() {
  test('cancel before load', () async {
    final request = PageRequest()..cancel();
    await expectLater(
      request.load(Uri.parse('http://127.0.0.1:1')),
      throwsA(isA<Cancelled>()),
    );
  });
  test(
    'two pages, invalid JSON and cancellation use a real HTTP boundary',
    () async {
      final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
      addTearDown(() => server.close(force: true));
      final waiting = Completer<void>();
      server.listen((request) async {
        if (request.uri.path == '/slow') {
          waiting.complete();
          return;
        }
        request.response.headers.contentType = ContentType.json;
        request.response.write(
          request.uri.path == '/bad'
              ? '{"items":[12]}'
              : request.uri.queryParameters['page'] == '2'
              ? '{"items":["B"],"next":null}'
              : '{"items":["A"],"next":2}',
        );
        await request.response.close();
      });
      final base = Uri.parse('http://127.0.0.1:${server.port}');
      final first = await PageRequest().load(base);
      final second = await PageRequest().load(
        base.replace(queryParameters: {'page': '${first.next}'}),
      );
      expect([...first.items, ...second.items], ['A', 'B']);
      expect(second.next, isNull);
      await expectLater(
        PageRequest().load(base.resolve('/bad')),
        throwsFormatException,
      );
      final request = PageRequest();
      final done = expectLater(
        request.load(base.resolve('/slow')),
        throwsA(isA<Cancelled>()),
      );
      await waiting.future.timeout(const Duration(seconds: 3));
      request.cancel();
      await done;
    },
  );
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.