To Download a File in Dart with minimal memory usage, you can use the http
package to stream the data directly to a file, avoiding loading the entire file into memory.
Here’s an efficient way to download and save a file:
Steps:
- Use the
http
package to make the request. - Stream the response body directly to a file using Dart’s
File
class andIOSink
.
Code Example:
import 'dart:io';
import 'package:http/http.dart' as http;
Future<void> downloadFile(String url, String savePath) async {
// Open a connection to the file
final file = File(savePath);
final sink = file.openWrite();
try {
// Make the HTTP GET request
final response = await http.Client().send(http.Request('GET', Uri.parse(url)));
// Check if the response is successful
if (response.statusCode == 200) {
// Stream the response body to the file
await response.stream.pipe(sink);
print('File downloaded successfully to $savePath');
} else {
print('Failed to download file: ${response.statusCode}');
}
} catch (e) {
print('Error downloading file: $e');
} finally {
// Close the file stream
await sink.close();
}
}
void main() async {
final url = 'https://example.com/file.zip'; // Replace with your file URL
final savePath = 'downloaded_file.zip'; // Replace with your desired save path
await downloadFile(url, savePath);
}
How It Works:
- Streaming Response: The
response.stream
provides a stream of the response body, which is directly piped to the file usingsink
. - Minimal Memory Usage: Since the data is streamed in chunks, the memory usage remains low, regardless of file size.
- Error Handling: The
try-catch
block ensures you handle exceptions gracefully (e.g., network issues or file write errors).
Key Benefits:
- Memory Efficient: Avoids loading the whole file into memory.
- Simple and Direct: Uses built-in Dart tools (
File
,IOSink
) and a widely-used package (http
).
Make sure to add the http
package to your pubspec.yaml
:
dependencies:
http: ^1.0.0
Run flutter pub get
or dart pub get
after adding the dependency.
Note: This is the client side of a Spring Boot Backend where I resolved similar issue https://programtom.com/dev/2025/01/18/ioexception-stream-closed-when-having-responseentity-a-file/