如何在状态更改后强制小部件重新创建自身?

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

我正在学习如何在 Flutter 中与图像交互,在我尝试的过程中photo_view我遇到了一个奇怪的交互,这让我想知道小部件是如何工作的。

所以我有 2 张图片。第一个的高度 > 宽度,第二个则相反。 但我想将它们都显示在一个正方形中,所以这就是我的代码:

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

放置在这个小部件树中的:

 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")),
      )
    ],
  ),
);

我一开始就得到了我想要的结果:

但是如果我点击按钮并切换图像的路径,我会得到这个:

(如果我再次切换,我会回到第一个屏幕)

当小部件的状态发生变化时,小部件是否应该重新创建自己? 我是 flutter 的新手,我真的不明白为什么会这样以及如何解决它...

强制重新创建小部件的最简单解决方案是使用键。类似的东西应该有所帮助(如果我很好地理解你的问题):

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