exportFile static method

Future<void> exportFile({
  1. required List<int> bytes,
  2. required String fileName,
  3. bool openAfterDownload = true,
})

Generic Export Method

Implementation

static Future<void> exportFile({
  required List<int> bytes,
  required String fileName,
  bool openAfterDownload = true,
}) async {
  try {
    if (kIsWeb) {
      final blob = html.Blob([bytes]);

      final url = html.Url.createObjectUrl(blob);

      final anchor = html.AnchorElement(href: url)
        ..download = fileName
        ..style.display = 'none';

      html.document.body?.append(anchor);

      anchor.click();
      anchor.remove();

      html.Url.revokeObjectUrl(url);

      debugPrint('$fileName downloaded successfully');
    } else {
      final directory = await getApplicationDocumentsDirectory();

      final file = File('${directory.path}/$fileName');

      await file.writeAsBytes(bytes, flush: true);

      debugPrint('Saved: ${file.path}');

      if (openAfterDownload) {
        await OpenFilex.open(file.path);
      }
    }
  } catch (e, stackTrace) {
    debugPrint('Export Error: $e');
    debugPrintStack(stackTrace: stackTrace);
  }
}