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

Flutter Stack布局中ListView叠放Container报最大宽度边界错误如何解决

问题排查与修复

错误根源

  • Positioned组件仅配置了top属性,未指定任何水平方向约束(left/right/width),导致其子组件没有明确的宽度边界。ListView默认会尝试占满父组件提供的最大可用宽度,父组件宽度无上限时就会触发最大宽度边界报错。
  • 额外问题:Stack的父容器高度仅为屏幕高度的1/1.6,但Positioned包裹的Container硬编码高度为800,会出现垂直方向溢出的问题。

修复方案

给Positioned补充水平方向约束即可解决宽度报错问题,可选方案如下:

  1. 若需要ListView占满Stack的全部宽度,同时给Positioned设置left: 0和right: 0
  2. 若需要固定宽度,直接给Positioned设置width属性即可

同时建议将内部Container的高度适配父Stack的可用高度,避免垂直溢出。

修复后完整代码

import 'package:flutter/material.dart';

class TryScreen extends StatelessWidget {
  const TryScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final stackHeight = MediaQuery.of(context).size.height / 1.6;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Try Screen'),
      ),
      body: Container(
        height: stackHeight,
        child: Stack(
          children: [
            Container(
              color: Colors.lightBlueAccent,
              height: 250,
              width: double.maxFinite,
            ),
            Positioned(
              top: 10,
              left: 0,
              right: 0,
              child: Container(
                height: stackHeight - 10,
                child: ListView.builder(
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    itemCount: 2,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        margin: const EdgeInsets.only(bottom: 10),
                        color: Colors.blue,
                        height: 250,
                        width: 250,
                      );
                    }),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:48:01