Vectorr
Vectorr

Reputation: 19

Preview Picked Image in Flutter

Hi I am using the image_picker package in flutter to pick images and store them to firestore. I want to preview the image in a circle avatar before I actually upload it so how would I go about doing that? This is the code I have to pick the image:

String imageUrl = '';

  Future pickImage(ImageSource imageSource) async {
    ImagePicker imagePicker = ImagePicker();
    XFile? file = await imagePicker.pickImage(
        source: imageSource);

    if (file == null) return;

    String uniqueFileName = DateTime
        .now()
        .millisecondsSinceEpoch
        .toString();

    //Getting a reference to storage root
    Reference referenceRoot = FirebaseStorage.instance.ref();
    Reference referenceDirImages = referenceRoot.child(
        'images');
    //Create a reference for the image to be stored

    Reference referenceImageToUpload = referenceDirImages
        .child(uniqueFileName);

    try {
      //Store the file
      await referenceImageToUpload.putFile(File(file.path));
      //  Success: get download URL
      imageUrl =
      await referenceImageToUpload.getDownloadURL();
    } catch (error) {
      //  Some error occurred
    }
  }

This is where I ask the user to pick the image either from the gallery or camera and then in the circle avatar I want them to preview the image before actually uploading it:

InkWell(
                   child: CircleAvatar(
                     backgroundColor: Colors.blue[900],
                     radius: 100,
            ),
                  onTap: () async {
                    return showDialog(context: context, builder: (context) {
                      return Center(
                        child: SizedBox(
                          height: 200,
                          child: AlertDialog(
                            backgroundColor: Colors.blue[900],
                            actionsPadding: const EdgeInsets.all(10.0),
                             content: Center(
                               child: Column(
                                 mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  ElevatedButton(onPressed: () {
                                    pickImage(ImageSource.gallery);
                                  },
                                      style: ButtonStyle(
                                        backgroundColor: MaterialStateProperty.all(Colors.white)
                                      ),
                                      child: const Text("Gallery",
                                      style: TextStyle(
                                        color: Colors.black
                                      ),)),

                                  const SizedBox(
                                    height: 10,
                                  ),
                                  ElevatedButton(
                                    style: ButtonStyle(
                                      backgroundColor: MaterialStateProperty.all(Colors.white)
                                    ),
                                    onPressed: () {
                                      pickImage(ImageSource.camera);
                                    },
                                    child: const Text("Camera", style: TextStyle(
                                      color: Colors.black
                                    ),),
                                  )
                                ],
                            ),
                             ),
                          ),
                        ),
                      );
                    }
                    );

                  }
                ),

Thanks!

Upvotes: 0

Views: 631

Answers (1)

Gwhyyy
Gwhyyy

Reputation: 9196

Well you need to separate your functions into sub-functions, but first I will create this variable:

  File? imageFile;

then it should be a function that picks that image from the device and update the state of the imageFile variable we made.

 Future pickImage(ImageSource imageSource) async {
  ImagePicker imagePicker = ImagePicker();
  XFile? file = await imagePicker.pickImage(source: imageSource);

  if (file == null) return;


setState(() {
  imageFile = File(file.path);
});
  
}

and a method that returns the widget which will show the actual image we pick:

Image genratePreviowWidget(File file) {
  return Image.file(file);
}

and in your UI, you should show it under an if condition like this:

Column(
children: [
 if(imageFile != null)  genratePreviowWidget(imageFile ),
 ],
),

now you have a method that pick the image and show it directly in your UI after it's done.

forwe still have that imageFile, so you can simply upload it ( confirm uploading it) from a separate method:

Future confirmUpload(File file) async {
    String uniqueFileName = DateTime.now().millisecondsSinceEpoch.toString();
  
  //Getting a reference to storage root
  Reference referenceRoot = FirebaseStorage.instance.ref();
  Reference referenceDirImages = referenceRoot.child('images');
  //Create a reference for the image to be stored

  Reference referenceImageToUpload = referenceDirImages.child(uniqueFileName);


    try {
    //Store the file
    await referenceImageToUpload.putFile(file);
    //  Success: get download URL
    imageUrl = await referenceImageToUpload.getDownloadURL();
  } catch (error) {}
}

and you will need to call it when you want to upload it like this:

confirmUpload(imageFile);

Upvotes: 1

Related Questions