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

Flutter:ListView内的Card无法限制最大宽度问题

问题原因及解决方案

核心原因

你的Card被包裹在SizedBox(width:50)里却占满屏幕宽度,是因为**ListView的子项默认会被强制拉伸至ListView的水平宽度**,SizedBox设置的width被ListView的布局约束直接覆盖,导致子项必须填满整个屏幕宽度。

解决方案

你可以通过给子项添加Align组件,让子元素按照自身尺寸布局,而非被ListView强制拉伸:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: const [
        Align(
          alignment: Alignment.centerLeft, // 可根据需求调整对齐位置
          child: SizedBox(
            width: 50,
            child: Card(
              child: Row(
                children: [
                  Text('test'),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}

也可以直接给Card指定宽度,同时用Align包裹避免被拉伸:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      children: const [
        Align(
          child: Card(
            child: SizedBox(
              width: 50,
              child: Row(
                children: [
                  Text('test'),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}

额外说明

Row组件默认会尽可能占据可用水平空间,但只要父级(SizedBox或Card)的宽度被限制,Row就只会在这个限制范围内布局,不会超出。

内容的提问来源于stack exchange,提问作者João Abrantes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 16:13:21