Flutter代码出现"BoxConstraints forces an infinite width"错误的原因是什么?
错误触发原因
- 核心错误出现在Card内部的Row嵌套ListTile部分:ListTile默认会尝试填充父组件提供的最大横向宽度,但Row组件不会给子元素限制横向最大宽度,只会让子元素自行决定宽度,这就导致ListTile尝试获取无限宽度,触发约束报错。
- 次要逻辑问题:你给TextField的InputDecoration设置了
BoxConstraints(maxWidth: 300),但这个约束优先级低于外层Container的约束,而你外层的Container没有设置宽度限制,放在Column中时会默认拉伸到屏幕宽度,不符合你限制输入框宽度的预期。
解决方法
- 给Row内的ListTile外层加
Expanded组件,强制ListTile仅占用Row的可用宽度,不会无限延伸,修改后的代码如下:
Card( elevation: 7.0, color: Colors.white, margin: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0), child: Row( children: const [ // 新增Expanded包裹ListTile Expanded( child: ListTile( minLeadingWidth: 6.0, leading: Icon( Icons.people_alt_rounded, ), title: Text( 'Sign up with apple', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 10.0, ), ), ), ), ], ), )
- 若要实现输入框最大宽度300的效果,把宽度约束移到TextField外层的Container上,不要写在InputDecoration中,修改示例:
Container( color: Colors.white, // 约束移到此处 constraints: const BoxConstraints(maxWidth: 300.0), child: const TextField( decoration: InputDecoration( filled: true, labelText: 'Username', // 删掉此处原有的constraints配置 ), ), ),
密码输入框也按照同样逻辑修改即可。
内容的提问来源于stack exchange,提问作者Bruce Zhang
相关产品推荐
相关产品推荐

