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

Flutter实现两固定高度容器间自适应高度容器的方案

解决Flutter中两个固定高度容器间自适应高度组件的问题

要让PatientList在两个固定高度的容器之间自适应剩余屏幕空间,核心是用Expanded组件分配剩余空间,同时移除组件内部的固定高度约束。具体操作如下:

1. 调整父组件布局

确保PatientList被包裹在Column布局中,上下放置固定高度容器,并用Expanded包裹PatientList:

Column(
  children: [
    // 顶部固定高度容器(红框)
    Container(height: 120, color: Colors.red),
    // 自适应高度的PatientList
    Expanded(child: PatientList()),
    // 底部固定高度容器(红框)
    Container(height: 80, color: Colors.red),
  ],
)

2. 修改PatientList组件代码

移除原代码中Container的固定height属性(冗余的width设置也可省略,Container在Column中默认占满宽度):

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

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(color: kSecondcolor),
      // 移除固定height,无需手动设置width
      child: ListView.builder(
        scrollDirection: Axis.vertical,
        itemBuilder: (context, index) {
          Patients patients = patientList[index];
          return Padding(
            padding: const EdgeInsets.only(left: 20, right: 20, bottom: 10),
            child: GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => InformationPatient(patients),
                  ),
                );
              },
              child: Card(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(left: 5, top: 8, bottom: 10),
                      child: Text(
                        '${patientList[index].name} ${patientList[index].firstname}',
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 3, left: 5),
                      child: Text(
                        'ID #${patientList[index].id}',
                        style: TextStyle(color: Colors.black.withOpacity(0.5)),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        itemCount: patientList.length,
      ),
    );
  }
}

关键说明

  • Expanded会自动计算Column中除上下固定容器外的剩余空间,让PatientList填满该区域,完美适配不同屏幕高度。
  • 移除固定height后,ListView.builder在空间不足时会自动启用滚动,保证内容可正常浏览。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:50:23