cancelable_http_client 1.0.0 copy "cancelable_http_client: ^1.0.0" to clipboard
cancelable_http_client: ^1.0.0 copied to clipboard

A cancelable HTTP client is a wrapper over `http.Client` that allows to cancel a request or the operation of receiving data from the response or the operation of sending data via request.

example/example.dart

import 'dart:async';
import 'dart:convert';

import 'package:cancelable_http_client/cancelable_http_client.dart';
import 'package:http/http.dart';

Future<void> main() async {
  for (final timeout in [0, 50, 1000]) {
    final cts = CancellationTokenSource();
    final timer = Timer(Duration(milliseconds: timeout), () {
      print('Canceling');
      cts.cancel();
    });

    final token = cts.token;
    final client = CancelableClient(token);
    final url = Uri.parse('https://pub.flutter-io.cn/api/package-names');
    Response? response;
    try {
      response = await client.get(url);
    } on TaskCanceledException {
      print('Canceled');
    } finally {
      timer.cancel();
    }

    if (response != null) {
      if (response.statusCode != 200) {
        throw StateError('Http error (${response.statusCode})');
      }

      final body = response.body;
      final map = jsonDecode(body) as Map;
      final list = map['packages'];
      print('First names: ${list.take(5)}');
    }

    print('-' * 40);
  }
}
0
likes
0
points
67
downloads

Publisher

unverified uploader

Weekly Downloads

A cancelable HTTP client is a wrapper over `http.Client` that allows to cancel a request or the operation of receiving data from the response or the operation of sending data via request.

Repository (GitHub)
View/report issues

Topics

#cancellation #http #http-client #network #streams

License

unknown (license)

Dependencies

http, multitasking

More

Packages that depend on cancelable_http_client