1
votes

i want to upload image to Firebase Storage, but I noticed most of the code available online (except documentation) has deprecated. as i am new to flutter, I read documentation for image picker and firestore. i was able to figure out image picker, but uploading in bucket of firestore is giving me the tough time.

below is the code for imagepicker,that i managed to do correctly:

 File _image;
     final picker = ImagePicker();
    
    Future getImage() async {
          final pickedFile =  await ImagePicker().getImage(source: ImageSource.camera);
          setState(() {
            if (pickedFile != null) {
              _image = File(pickedFile.path);
    
    
            } else {
              print('No image selected.');
            }
    
          });
        }

now i dont know how to complete the upload to Firebase Storage function:

Future UploadImage(BuildContext context) async{

String filename = basename(_image.path);
firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;



// how to proceed?


}
1
The documentation for Firebase Storage has up-to-date code samples for uploading: firebase.flutter.dev/docs/storage/usage#uploading-filesFrank van Puffelen

1 Answers

9
votes

Since you have the file name. I will use your code only for that.

String filename = basename(_image.path);

Reference storageReference = FirebaseStorage.instance.ref().child("<Bucket Name>/$filename");

After having a reference to your bucket now you need to put the file in that bucket.

final UploadTask uploadTask = storageReference.putFile(file);

Now you need the url of the image. For that you need to wait till the upload completes.

final TaskSnapshot downloadUrl = (await uploadTask);

Now after this is done you can get the URL of the file using

final String url = await downloadUrl.ref.getDownloadURL();

This answer is for the version number firebase_storage: ^5.2.0

Hope this helps. Let me know if any doubts.