Using dart to download a file Using dart to download a file dart dart

Using dart to download a file


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.


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());}


The python example linked to in the question involves requesting the contents of example.com and writing the response to a file.

Here is how you can do something similar in Dart:

import 'dart:io';main() {  var url = Uri.parse('http://example.com');  var httpClient = new HttpClient();  httpClient.getUrl(url)    .then((HttpClientRequest request) {      return request.close();    })    .then((HttpClientResponse response) {      response.transform(new StringDecoder()).toList().then((data) {        var body = data.join('');        print(body);        var file = new File('foo.txt');        file.writeAsString(body).then((_) {          httpClient.close();        });      });    });}