You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter设置Container占满宽度报BoxConstraints forces an infinite width错误如何解决

问题原因

Positioned组件仅设置left: 0时,没有明确的横向约束边界,其子组件设置double.infinity宽度时,Flutter无法计算出实际的渲染宽度,因此会抛出BoxConstraints forces an infinite width错误。

效果示意图

解决方法

给包裹橙色Container的Positioned组件同时添加right: 0属性,让其左右边界都贴合父Stack的横向边缘,即可自动占满全部可用宽度,无需手动设置宽度值。

修改后的代码如下:

Container(
  padding: EdgeInsets.symmetric(horizontal: 20),
  height: 205,
  color: Colors.grey,
  //margin: EdgeInsets.symmetric(vertical: 20),
  child: Stack(
    children: [
      Positioned(
        left: 0,
        right: 0, // 新增该行固定右边界
        bottom: 0,
        child: Container(
          height: 185,
          // 删除原width属性
          color: Colors.deepOrange,
        ),
      ),
      Positioned(
        right:0,
        top:0,
        child: Image.asset('assets/images/book-1.png',width: 150,),
      ),
    ],
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:06:03