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

Flutter:Card内嵌套ListView底部出现多余空白的问题

为何Card底部会显示多余空白?

Card底部存在多余空白

当设置itemCount: 0时,显示效果如下:

itemCount为0时的Card状态

问题原因

这个多余空白是ListView.separated启用shrinkWrap: true时的高度计算特性导致的:

  • ListView在shrinkWrap模式下会自动适配内容高度,但默认会保留平台相关的额外内边距
  • 结合Card的包裹,这部分额外空间就会以空白形式显示在底部

解决方案

有两种简单的解决方式:

方式1:移除ListView默认内边距

直接给ListView.separated添加padding: EdgeInsets.zero参数,消除默认的额外内边距:

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    List<String> words = ['hello', 'world', 'flutter'];

    return Scaffold(
      backgroundColor: Colors.green,
      appBar: AppBar(
        title: const Text('Test'),
        centerTitle: true,
      ),
      body: Card(
        child: ListView.separated(
          separatorBuilder: (context, index) {
            return const Divider(
              color: Colors.black,
            );
          },
          itemCount: words.length,
          shrinkWrap: true,
          padding: EdgeInsets.zero, // 添加该行移除默认内边距
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(words[index]),
            );
          },
        ),
      ),
    );
  }
}

方式2:用Column替代ListView(适合少量数据)

如果列表数据量不大,直接使用Column构建列表,避免ListView的shrinkWrap特性带来的高度计算问题:

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    List<String> words = ['hello', 'world', 'flutter'];

    return Scaffold(
      backgroundColor: Colors.green,
      appBar: AppBar(
        title: const Text('Test'),
        centerTitle: true,
      ),
      body: Card(
        child: Column(
          mainAxisSize: MainAxisSize.min, // 让Column仅占用内容所需高度
          children: [
            for (int i = 0; i < words.length; i++)
              Column(
                children: [
                  ListTile(title: Text(words[i])),
                  // 最后一个item后不添加分隔线
                  if (i != words.length - 1)
                    const Divider(color: Colors.black),
                ],
              ),
          ],
        ),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 02:54:22