如何设置容器相对高度并实现两端容器自适应中间固定高度容器?
如何设置容器相对高度并实现两端容器自适应中间固定高度容器?
嘿,这个需求我之前也碰到过!要让Row里两端的容器自动匹配中间固定高度容器的高度,咱们用Flutter的IntrinsicHeight组件配合CrossAxisAlignment.stretch就能轻松搞定,具体思路和代码如下:
核心思路
IntrinsicHeight会让它的子组件(这里是Row)的高度自适应子项里固有高度最高的那个,也就是中间固定了100高度的容器;再给Row设置crossAxisAlignment: CrossAxisAlignment.stretch,就能让两端的Expanded容器自动拉伸到Row的高度,完美匹配中间容器的高度。
完整代码示例
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // 左侧自适应高度的容器 Expanded( child: Container( color: Colors.orangeAccent, child: const Center(child: Text("左侧容器")), ), ), // 中间固定高度的容器 Expanded( child: Container( height: 100, color: Colors.green, child: const Center(child: Text("中间固定高度容器")), ), ), // 右侧自适应高度的容器 Expanded( child: Container( color: Colors.blueAccent, child: const Center(child: Text("右侧容器")), ), ), ], ), ), ), ), ); } }
代码说明
IntrinsicHeight:强制Row的高度由子项的固有高度决定,这里就是中间容器的100高度。crossAxisAlignment: CrossAxisAlignment.stretch:让Row里的每个Expanded子组件都拉伸到Row的高度,这样两端的容器就自动和中间的一样高了。- 两端的容器不需要设置
height属性,完全由父组件的布局约束自动适配。
这样运行起来,左右两个容器就会和中间固定高度的容器保持一致的高度啦!
备注:内容来源于stack exchange,提问作者user20778124
相关产品推荐
相关产品推荐

