【问题标题】:flutter set state like instagram post颤振设置状态,如 instagram 帖子
【发布时间】:2025-12-18 03:05:02
【问题描述】:

对不起我的英语我希望我能准确地解释我想要什么。如果我在 else 部分创建 imageCount 变量,则设置状态不会发生。但是如果我在全局范围内创建它,它会变为设置状态,但这次它会在每个图像上发生变化。这是我的代码,就像 Instagram 一样,帖子即将发布,它们在另一个下方列出。我也在尝试打印图像编号,现在我应该如何定义这个变量?无论用户滚动浏览哪个帖子,其数量都会增加 1。

Widget _imageDisplay(int index) {

if (postsList == null) {
  return null;
} else {
int imageCount=1;  //this variable
  return Container(
    color: Colors.white,
    width: MediaQuery.of(context).size.width,
    height: MediaQuery.of(context).size.height * 0.5,
    child: Stack(children: [
      PhotoViewGallery(
        onPageChanged: (index) {
          setState(() {
            imageCount = index + 1;
          });

        },
        customSize: MediaQuery.of(context).size,
        backgroundDecoration: BoxDecoration(color: Colors.white),
        pageOptions: _photoPageOpt(index),
      ),
      Align(
          alignment: Alignment.topRight,
          child: Text(imageCount.toString() +
              '/' +
              postsList[index].images.length.toString()))
    ]),
  );
}

}

【问题讨论】:

    标签: flutter dart setstate


    【解决方案1】:

    变量imageCount 需要成为Stateful Widget 状态的一部分,否则setState 不起作用。所以它需要在你的扩展State<MyWidget>的类中声明。

    在调用_imageDisplay时,如果postsList为null,则需要返回一个widget,可以返回一个空容器,如SizedBox()

    现在,为了控制变量imageCount 更新时的逻辑,您需要将逻辑放在setState 函数中。

    不幸的是,我不太了解您到底想要实现什么,但尝试将其表达为一个可以控制图像计数器更新的条件,如下所示:

    setState(() {
        if(condition) {
            imageCount = index + 1;
        }
    });
    

    【讨论】: