How to force a widget to recreate itself after a state changed?

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...



Read more here: https://stackoverflow.com/questions/64953484/how-to-force-a-widget-to-recreate-itself-after-a-state-changed

Content Attribution

This content was originally published by Yoann Far at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: