1
votes

I am learning how to interact with images in Flutter, and while I was trying photo_view I met a weird interaction which made me wonder how widgets work.

So I have 2 images. First one with its height > its width, and the second one the other way around. But I want to display them both in a square, so this is what my code looks like :

 Widget _getPhotoView(String path) => AspectRatio(
    aspectRatio: 1,
    child: ClipRect(
      child: PhotoView(
        minScale: PhotoViewComputedScale.covered,
        imageProvider: AssetImage(path),
      ),
    ),
  );

Which is placed in this widgets tree :

 Widget build(BuildContext context) {
return Scaffold(
  body: ListView(
    children: [
      Container(
        height: MediaQuery.of(context).size.width,
        child: _onStart
            ? _getPhotoView("assets/images/ig3.jpg")
            : _getPhotoView("assets/images/ig4.jpg"),
      ),
      Container(
        color: Colors.yellow,
        child: FlatButton(
            onPressed: () {
              setState(() {
                _onStart = !_onStart;
              });
            },
            child: Text("Switch images")),
      ),
      Container(
        height: MediaQuery.of(context).size.width,
        child: _onStart
            ? _getPhotoView("assets/images/ig4.jpg")
            : _getPhotoView("assets/images/ig3.jpg"),
      ),
      Container(
        color: Colors.yellow,
        child: FlatButton(
            onPressed: () {
              setState(() {
                _onStart = !_onStart;
              });
            },
            child: Text("Switch images")),
      )
    ],
  ),
);

I get the result I want on start :

2

But if I click on the button and switch the path of the images, I get this :

3

(if I switch again I get back to the first screen)

When the state of a widget has changed, isn't the widget suppose to recreate itself? I am new to flutter and I don't really understand why this is happening and how to fix it...

1

1 Answers

1
votes

The easiest solution to force widget recreation is to use keys. Something like that should help (if I understood your problem well):

  Widget _getPhotoView(String path) => AspectRatio(
        aspectRatio: 1,
        child: ClipRect(
          child: PhotoView(
            key: ValueKey(path),
            minScale: PhotoViewComputedScale.covered,
            imageProvider: AssetImage(path),
          ),
        ),
      );