You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发:如何更新不在build Widget内的字段实现实时刷新

问题原因及解决方案

问题本质

你调用setState只会触发当前ShoppingState的build方法重绘,而_tempQuan1渲染在AwesomeDialog的组件树中,这个对话框是挂载在全局Overlay层的,不属于ShoppingState的组件树范围,所以就算你更新了_tempQuan1的数值,已经渲染完成的对话框也不会同步刷新。
而_tempQuan2直接在ShoppingState的build方法中渲染,所以调用setState后能正常更新。

修复方案

最简单的方式是给对话框的内容套一层StatefulBuilder,拿到对话框专属的状态更新方法,修改showBuyPopup方法的代码即可:

showBuyPopup() async {
  AwesomeDialog(
    context: context,
    dialogType: DialogType.NO_HEADER,
    // 用StatefulBuilder包裹原有的body内容
    body: StatefulBuilder(
      builder: (context, setStateDialog) {
        return Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: <Widget>[
                  Container(
                    width: 32.0,
                    height: 25.0,
                    child: Text(
                      _tempQuan1.toString(),
                    ),
                  ),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Material(
                      child: InkWell(
                        splashColor: Theme.of(context).primaryColor,
                        onTap: () {
                          // 调用对话框的状态更新方法
                          setStateDialog(() {
                            _tempQuan1++;
                          });
                          print('increase');
                        },
                        child: Container(
                          width: 35.0,
                          height: 32.0,
                          decoration: BoxDecoration(
                            color: Theme.of(context).primaryColorDark.withOpacity(0.9),
                            borderRadius: BorderRadius.circular(8.0),
                          ),
                          child: Icon(
                            Icons.add,
                            color: Colors.white,
                            size: 18.0,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 10.0,
              ),
            ],
          ),
        );
      }
    ),
    buttonsTextStyle: Theme.of(context).textTheme.bodyText2,
    showCloseIcon: false,
    btnCancelOnPress: () {},
    btnOkOnPress: () async {},
  )..show();
}

如果用Getx没生效,是因为你没有在对话框内用Obx包裹显示_tempQuan1的Text组件,只要给对应Text套上Obx就能正常响应变量变化。

内容的提问来源于stack exchange,提问作者inter cretasyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:06:03