Last active
March 23, 2022 22:26
-
-
Save Hesamedin/040fdac28936874a282cef44e53cfbb2 to your computer and use it in GitHub Desktop.
This code belongs to this article: https://hesam-kamalan.medium.com/flutter-web-download-file-from-firebase-6a5c35ef7613
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dart imports: | |
import 'dart:convert'; | |
import 'dart:typed_data'; | |
// Flutter imports: | |
import 'package:flutter/foundation.dart' show kIsWeb; | |
// Package imports: | |
import 'package:get_it/get_it.dart'; | |
import 'package:universal_html/html.dart'; | |
import 'package:url_launcher/url_launcher.dart'; | |
// Project imports: | |
import './modules/managers/firebase_manager.dart'; | |
/// Open file in a browser | |
Future<void> launchURL(String? url) async { | |
if (url == null) return; | |
await canLaunch(url) ? await launch(url) : throw 'Could not launch $url'; | |
} | |
/// Download file from firebase | |
Future<void> downloadFile(String fileName, String pathToFile, String url) async { | |
if (pathToFile.isEmpty) return; | |
if (!kIsWeb) return; | |
Uint8List? data = await FirebaseStorage.instance.ref(pathToFile).getData(); | |
// Fallback option | |
if (data == null) return await launchURL(url); | |
String encodedData = base64Encode(data); | |
try { | |
AnchorElement(href: 'data:application/octet-stream;charset=utf-8;base64,$encodedData') | |
..setAttribute('download', fileName) | |
..click(); | |
} catch (error) { | |
// Fallback option | |
await launchURL(url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment