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

The `defer` is a small function intended to simplify the use of functions that require to execute `postponed` actions.

example/example.dart

import 'dart:async';

import 'package:defer/defer.dart';
import 'package:http/http.dart' as http;

Future<void> main() async {
  final uri = Uri.parse('https://pub.dev/feed.atom1');
  final bytes = <int>[];
  final client = http.Client();
  await defer(() async => client.close(), () async {
    final request = http.Request('GET', uri);
    final response = await client.send(request);
    if (response.statusCode != 200) {
      throw StateError('Http error (${response.statusCode}): $uri');
    }

    final iterator = StreamIterator(response.stream);
    await defer(iterator.cancel, () async {
      while (await iterator.moveNext()) {
        bytes.addAll(iterator.current);
      }
    });
  });

  final text = String.fromCharCodes(bytes);
  print(text);
}
0
likes
160
points
55
downloads

Publisher

unverified uploader

Weekly Downloads

The `defer` is a small function intended to simplify the use of functions that require to execute `postponed` actions.

Repository (GitHub)
View/report issues

Documentation

API reference

License

BSD-3-Clause (license)

More

Packages that depend on defer