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
相关产品推荐
相关产品推荐

