Manage Firebase storage using flutter

To upload and download any image, pdf, doc file in cloud then firebase is best option.

More about firebase storage follow link





Add Following dependecies inside pubspec.yaml file

dependencies:
flutter:
sdk: flutter
cloud_firestore: ^2.2.0
firebase_storage: ^8.1.0
You have to set rules inside your firestore to access files
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write
    }
  }
}


Now inside your firebase storage create folder whatever you want right now we are using "uploads/ "



First you have install firestore inside your flutter project.

flutter pub add firebase_storage

Once done with that rebuild your project.

flutter run

Now initialize firebase inside initState()

Firebase.initializeApp();
Once initilize completed create reference of fireStore
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');

Below code is for upload  files inside firebase storage.
Future<String> uploadImageToFirebase(
    BuildContext context, File imageFile) async {
  Firebase.initializeApp();
  String imageUrl = "";
String fileName = basename(imageFile.path);
Reference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(imageFile);
await uploadTask.whenComplete(() async {
await firebaseStorageRef.getDownloadURL().then((value) async {
imageUrl = value;
});
});
return imageUrl;
}

And to download firebase files use below code.
Future<String> getImageURL(String url) async {
final ref = FirebaseStorage.instance.ref().child('upload');
return await ref.getDownloadURL();
}

The full code of how to pick file from gallary and upload it to firebase
add image picker dependecies in pubspec.yaml
image_picker: ^0.7.5+2

GestureDetector(
onTap: () {
_imgFromGallery(context);
},
child: MyCircularImage.fromImageUrl(_imageUrl, "")),

_imgFromGallery(BuildContext context) async {
var pickFile = await ImagePicker()
.getImage(source: ImageSource.gallery, imageQuality: 10);

if (pickFile != null) {
_image = File(pickFile.path);
await uploadImageToFirebase(context, _image).then((value) {
setState(() {
_imageUrl = value;
});
});
} else {
print('No image selected.');
}
}






Comments

Popular posts from this blog

Flutter Bloc Pattern 8.0.0 Call API

Learn SQLite using flutter

Search by character in flutter