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

Flutter Stack组件中使用TextField出现无界宽度报错该如何解决?

问题根源

  • 你使用的Positioned仅配置了底部约束,未设置水平方向约束,导致子组件Row的宽度上限为无穷大
  • Expanded/Flexible需要在有限宽度的父Flex容器中才能计算自身占用空间,TextField本身也要求父组件提供有限的宽度约束

你之前尝试设置mainAxisSize: MainAxisSize.min和FlexFit.loose的方案反而会让Row的宽度由子组件撑开,TextField依然拿不到有限的宽度约束,所以会触发第二个报错。

解决方案

直接给Positioned组件增加left: 0和right: 0属性,强制它的宽度和父Stack保持一致,不需要修改Row的mainAxisSize,也不需要替换Expanded为Flexible,即可满足布局需求。

修改后的完整代码如下:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Stack(
      children: [
        // TODO: ListView here
        Positioned(
          bottom: 0.0,
          left: 0.0, // 新增水平左约束
          right: 0.0, // 新增水平右约束
          child: Row(
            children: [
              const Expanded(
                child: TextField(
                  decoration: InputDecoration(
                    hintText: "Type here"
                  ),
                ),
              ),
              SizedBox(
                height: 30.0,
                width: 30.0,
                child: IconButton(
                  icon: const Icon(Icons.send),
                  onPressed: () {},
                ),
              ),
            ],
          ),
        ),
      ],
    ),
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:15:08