Skip to content

Instantly share code, notes, and snippets.

@isaiasmatewos
Created November 2, 2022 18:22
Show Gist options
  • Save isaiasmatewos/c15c4d75ce501437bd2be6eea6d0acb9 to your computer and use it in GitHub Desktop.
Save isaiasmatewos/c15c4d75ce501437bd2be6eea6d0acb9 to your computer and use it in GitHub Desktop.
Function to download a file from Supabase storage and track download progress
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:supabase_flutter/supabase_flutter.dart';
Future<void> _downloadFileWithProgress(Map<String, String> headers,
String bucketId, String path, File downloadPath) async {
try {
setState(() {
_downloading = true;
});
final _path = _getFinalPath(bucketId, path);
final options = FetchOptions(headers: headers, noResolveJson: true);
final url = '${supabase.storage.url}/object/$_path';
final request = http.Request('GET', Uri.parse(url))
..headers.addAll(headers)
..body = json.encode({});
final response = request.send();
List<List<int>> chunks = [];
int downloaded = 0;
response.asStream().listen((event) {
event.stream.listen(
(value) {
// Display perecentage of completion
debugPrint(
'downloadPercentage: ${downloaded / (event.contentLength ?? 0) * 100}');
chunks.add(value);
downloaded += value.length;
setState(() {
_downloadProgress = downloaded / (event.contentLength ?? 0);
});
},
onDone: () async {
// Display perecentage of completion
debugPrint(
'downloadPercentage: ${downloaded / (event.contentLength ?? 0) * 100}');
// Save the file
final Uint8List bytes = Uint8List(event.contentLength ?? 0);
int offset = 0;
for (List<int> chunk in chunks) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
await downloadPath.create(recursive: true);
await downloadPath.writeAsBytes(bytes);
setState(() {
_downloading = false;
});
},
);
});
} catch (e) {
debugPrint(e.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment