Flutter点击按钮创建新Container,界面未更新的问题排查
问题分析与解决
你的代码点击按钮后界面不更新,核心原因是组件未使用StatefulWidget,导致setState无法触发UI重建。此外还有两处细节问题需要优化,以下是具体修正方案:
核心问题修正
setState是StatefulWidget专属的状态更新方法,如果你的组件是StatelessWidget,调用setState不会有任何效果。必须将组件改为StatefulWidget,并在对应的State类中管理_i状态。
额外细节优化
- 序号显示错误:你在
itemBuilder中使用$_i显示序号,会导致所有Container都显示当前的_i值(比如点击3次,所有容器都显示3),应该改用${index + 1}对应每个项的实际序号。 - 布局约束问题:原代码用
SingleChildScrollView嵌套ListView.builder容易引发滚动冲突,且Column中直接放滚动组件需要明确高度约束,改用Expanded包裹ListView即可解决布局溢出问题。 - 屏幕尺寸获取:确保
heightScreen和widthScreen通过MediaQuery.of(context).size正确获取,避免容器因尺寸为0而不可见。
修正后的完整代码
class ContainerListPage extends StatefulWidget { const ContainerListPage({super.key}); @override State<ContainerListPage> createState() => _ContainerListPageState(); } class _ContainerListPageState extends State<ContainerListPage> { int _i = 0; @override Widget build(BuildContext context) { final screenSize = MediaQuery.of(context).size; final heightScreen = screenSize.height; final widthScreen = screenSize.width; return Column( children: [ TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all<Color>(Colors.blue), ), onPressed: () { setState(() { _i++; print(_i); print("Fidase"); }); }, child: const Text('TextButton'), ), Expanded( child: ListView.builder( shrinkWrap: true, itemCount: _i, itemBuilder: (BuildContext ctxt, int index) { return Container( color: Colors.blueGrey, height: heightScreen * .08, width: widthScreen, child: Text("Container numero ${index + 1}"), ); }, ), ) ], ); } }
内容的提问来源于stack exchange,提问作者Lucas Barreto Luz
相关产品推荐
相关产品推荐

