flutterimagepicker

How to display picked image in a circle avatar in Flutter?


I have the following code which launches the image picker to select image from gallery.

File _image;
  final picker = ImagePicker();

  Future getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      _image = File(pickedFile.path);
    });
  }

After the image is selected, I want that image to be displayed in an already present CircleAvatar. The above method getImage() is called as shown below:

                InkWell(
                        onTap: getImage,
                        child: CircleAvatar(
                          backgroundColor: Colors.black,
                          radius: 40.0,
                          child: CircleAvatar(
                            radius: 38.0,
                            child: ClipOval(
                              child: Image.asset('images/newimage.png'),
                            ),
                            backgroundColor: Colors.white,
                          ),
                        )
                    ),

I have a ClipOval which is the child of the CircleAvatar and has a default AssetImage as its child . I am not able to figure out how to replace this placeholder image with the one that is picked from the gallery! Any help is appreciated.


Solution

  • You can use your _image variable to check if it is null or not and then accordingly set the image in ClipOval.

    InkWell(
      onTap: getImage,
      child: CircleAvatar(
        backgroundColor: Colors.black,
        radius: 40.0,
        child: CircleAvatar(
          radius: 38.0,
          child: ClipOval(
            child: (_image != null)
            ? Image.file(_image)
            : Image.asset('images/newimage.png'),
          ),
          backgroundColor: Colors.white,
        ),
      ),
    );