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

Flutter中如何为自定义Widget适配可用高度

解决Flutter自定义Widget适配不同页面可用高度的问题

问题分析

你的ShowTransactionWidget使用了固定高度500,这会导致在不同页面(比如NextScreen中上方已有占70%屏幕高度的组件)出现布局溢出或空间利用不合理的情况。要实现自适应可用高度,需要让Widget根据父容器的约束自动调整,而非使用固定值。

修改方案

1. 调整自定义Widget代码

移除Container的固定height,让它自动继承父组件的高度约束,同时确保内部Column能正确填充可用空间:

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

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.grey.shade200,
      child: Column(
        children: [
          Align(
            alignment: Alignment.centerLeft,
            child: Text(
              'Recent Transactions',
              style: TextStyle(
                color: Colors.blue,
                fontSize: 20
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: 100,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text('Hello $index'),
                );
              },
            ),
          )
        ],
      ),
    );
  }
}

2. 在页面中正确使用Widget

在NextScreen的Column中,用Expanded包裹ShowTransactionWidget,让它占据页面剩余的可用高度:

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(children: [
        Container(
          color: Colors.blue,
          height: MediaQuery.of(context).size.height * 0.70,
        ),
        // 使用Expanded让Widget占据剩余空间
        Expanded(
          child: ShowTransactionWidget(),
        ),
      ]),
    );
  }
}

原理说明

  • 移除固定高度后,ShowTransactionWidget的高度由父容器的约束决定,能适配不同页面的可用空间。
  • Expanded会告诉Column,将剩余的可用空间分配给包裹的ShowTransactionWidget,避免布局溢出,同时充分利用屏幕空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:35:50