Using dart to download a file

Shailen's response is correct and can even be a little shorter with Stream.pipe.

import 'dart:io';

main() async {
  final request = await HttpClient().getUrl(Uri.parse('http://example.com'));
  final response = await request.close();
  response.pipe(File('foo.txt').openWrite());
}

I'm using the HTTP package a lot. If you want to download a file that is not huge, you could use the HTTP package for a cleaner approach:

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

main() {
  http.get(url).then((response) {
    new File(path).writeAsBytes(response.bodyBytes);
  });
}

What Alexandre wrote will perform better for larger files. Consider writing a helper function for that if you find the need for downloading files often.

Tags:

Dart