Skip to content

Instantly share code, notes, and snippets.

@TheAlphamerc
Created March 4, 2020 02:45
Show Gist options
  • Save TheAlphamerc/b49893c67e69fb200b898663f257cc3c to your computer and use it in GitHub Desktop.
Save TheAlphamerc/b49893c67e69fb200b898663f257cc3c to your computer and use it in GitHub Desktop.
Flutter firebase utility to upload and delete file from firebase
import 'dart:io';
import 'package:path/path.dart' as Path;
import 'package:firebase_storage/firebase_storage.dart';
class FirebaseUtility{
static Future<String> uploadFileToFirebase(File file) async {
try {
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('feeds${Path.basename(file.path)}');
StorageUploadTask uploadTask = storageReference.putFile(file);
var snapshot = await uploadTask.onComplete;
if (snapshot != null) {
var url = await storageReference.getDownloadURL();
if (url != null) {
/// File Url
return url;
}
}
} catch (error) {
print(error);
return null;
}
}
/// [Delete file] from firebase storage
static Future<void> deleteFileFRomFirebase(String url, String baseUrl) async {
try {
String filePath = url.replaceAll(
new RegExp(
r'https://firebasestorage.googleapis.com/v0/b/[PROJECT NAME IN FIREBASE].appspot.com/o/'),
'');
filePath = filePath.replaceAll(new RegExp(r'%2F'), '/');
filePath = filePath.replaceAll(new RegExp(r'(\?alt).*'), '');
StorageReference storageReference = FirebaseStorage.instance.ref();
await storageReference.child(filePath).delete().catchError((val) {
print('[Error]' + val);
}).then((_) {
print('[Sucess] Image deleted');
});
} catch (error) {
print(error);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment