defer 1.0.0
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.
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);
}