Flutter中ListView内SizedBox设置宽度不生效如何解决?
Flutter ListView 内固定子元素宽度方案
问题根因
ListView 布局时会强制所有子元素的宽度匹配 ListView 自身的可用宽度,会忽略子元素本身声明的宽度约束,因此直接嵌套指定宽度的 SizedBox 无法生效。
修复方案
在 SizedBox 外层包裹 Align 或 Center 组件,这类组件会松绑 ListView 的紧约束,允许子元素使用自定义的尺寸。你可以通过 alignment 参数调整 Card 在 ListView 内的对齐位置。
修改后完整代码
Scaffold( appBar: AppBar( leading: Icon(Icons.arrow_back), centerTitle: true, title: Text("Select Time Slot"), ), body: ListView( children: <Widget>[ Align( // 可根据需求调整对齐方式:Alignment.center / Alignment.centerRight alignment: Alignment.centerLeft, child: SizedBox( width: 150, child: Card( // 可选添加内边距优化文字显示效果 child: Padding( padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16), child: Text( "11 AM - 1 PM", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), ), ), ) ], ), );
内容的提问来源于stack exchange,提问作者Pythopath
相关产品推荐
相关产品推荐

