You need to enable JavaScript to run this app. Flutter调用setState后Text组件文本值未更新问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用setState后Text组件文本值未更新问题求助

问题原因

test变量被定义在build方法内部,每次调用setState触发页面重绘时,都会重新执行build方法,test会被重新初始化赋值为hello,因此Text组件展示内容不会更新。你在点击回调中能打印出修改后的值,是因为打印操作执行在build方法重新初始化变量之前。

解决方法

将test变量提升为当前State类的成员属性,不要在build方法内部声明,修改后的代码示例如下:

class _YourPageState extends State<YourPage> {
  // 将test变量声明在build方法外,作为State类的成员属性
  var test = "hello";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(test),
        backgroundColor: Color.fromRGBO(58, 133, 191, 1),
      ),
      body: Column(
        children: [
          Row(children: [
            Text(test),
            IconButton(
              icon: Icon(Icons.delete_forever),
              color: Colors.red,
              onPressed: () {
                setState(() {
                  test = "notworking:(";
                });
              },
            ),
          ]),
        ],
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 06:27:02