Search code examples
flutterflutter-layoutflutter-dependenciesimagepicker

Working with Imager Picker Dependency in Flutter


I have a function in my application that helps the user pick Image from gallery or take a photo with camera.

  _getImage(ImageSource source) async {
    // ignore: deprecated_member_use
    File selectedImage = await ImagePicker.pickImage(
      source: source,
      imageQuality: 50,
      maxWidth: 400.0,
    ).whenComplete(() {
      setState(() {});
    });
    if (_imageFile == null) return;
    
    setState(() {
      _imageFile = selectedImage;
    });
  }

I am using this image_picker dependency and I followed the example I found therein and also examples of possible updates done by others online. From a suggestion on this stackoverflow question, I'm advised to add the whenComplete therein, which I did.

When I select an image from my gallery, it doesn't update the image view widget in my screen. Neither does the camera option work. What could I possibly be missing?

Here's my Image widget that displays the image:

return Stack(
    alignment: AlignmentDirectional.bottomCenter,
    children: <Widget>[
      Image.file(
        _imageFile,
        fit: BoxFit.cover,
        height: 250,
      ),
      Container(
        width: 250.0,
        height: 100.0,
        color: Colors.black54,
        child: Column(
          children: <Widget>[
            Text(
              'Change Image',
              style: TextStyle(
                color: Colors.white,
                fontSize: 22.0,
                fontWeight: FontWeight.w400,
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                //camera button
                IconButton(
                  icon: Icon(FontAwesomeIcons.camera),
                  onPressed: () => _getImage(ImageSource.camera),
                  color: kThemeStyleButtonFillColour,
                ),
                SizedBox(width: 20.0),
                IconButton(
                  icon: Icon(FontAwesomeIcons.fileImport),
                  onPressed: () => _getImage(ImageSource.gallery),
                  color: kThemeStyleButtonFillColour,
                ),
              ],
            ),
          ],
        ),
      ),
      SizedBox(height: 32.0),
    ],
  );

Solution

  • You're using the wrong logic inside if statement.

    Right way to do this,

    if(selectedImage != null) { Update image widget here }

    I think imageFile variable has not been assigned any file initially so the condition imageFile == null is always true and the image widget is never updated.