flutterdartfirebase-storageflutter-image-picker

Unable to upload image file to Firebase Storage - Flutter


I'm building a simple system to let the user upload their profile picture into their account. When they click on the widget it runs this function:

XFile? xFileImage;
File? image;

  Future pickImage() async {
    try {
      xFileImage = await ImagePicker().pickImage(
        source: ImageSource.gallery,
        imageQuality: 70,
      );
      if (xFileImage == null) return;
      final File imageFile = File(xFileImage!.path);
      setState(() {
        image = imageFile;
      });
    } on PlatformException catch (error) {
      print(error);
    }
  }

This function works fine. However, when I try to upload the image on Firebase Storage, the app throws this error:

[firebase_storage/unknown] The operation couldn’t be completed. Message too long

Here is the code snippet I use to upload the image on Firebase:

if (image != null) {
   final FirebaseStorage storage = FirebaseStorage.instance;

   await storage.ref().child('users/${state.user.userId}')
   .putFile(image!);
 }

I followed each step written in the Firebase Storage documentation, but I'm missing something.


Solution

  • I already ran this code on an Android/IOS simulator, so I know it works, but it's a bit different on a web platform.

    First, try something like this in the state of your StatefulWidget:

    import 'package:image_picker/image_picker.dart';
    File? _selectedImage;
    
    void _takePicture() async {
    final imagePicker = ImagePicker();
    final pickedImage =
        await imagePicker.pickImage(source: ImageSource.gallery, imageQuality: 70);
    
    if (pickedImage == null) {
      return;
    }
    
    setState(() {
      _selectedImage = File(pickedImage.path);
    });}
    

    Then you need a button to call this function:

    TextButton.icon(
      icon: const Icon(Icons.camera),
      label: const Text('Pick Image'),
      onPressed: _takePicture,)
    

    Finally, call another function like this to upload your image to the Firebase Storage:

    import 'package:firebase_storage/firebase_storage.dart';
    
    void _submit() async {
    final storageRef = FirebaseStorage.instance
      .ref()
      .child('image_name.jpg');
    
    await storageRef.putFile(_selectedImage!);
    final imageUrl = await storageRef.getDownloadURL();
    print(imageUrl);}  // for your reference
    

    Don't forget to handle errors using try-catch or other methods!