如何将IndexedStack组件的子项对齐到其父容器底部?
Flutter:让IndexedStack内的子容器对齐到黄色容器底部
问题场景:
现有代码中,黄色容器内的底部Positioned组件嵌套了IndexedStack,里面包含红、蓝、绿三个不同高度的容器。点击按钮切换显示时,只有绿色容器能对齐黄色容器底部,红、蓝容器均无法实现底部对齐。
问题原因:IndexedStack默认会以所有子组件中最高的那个高度作为自身高度,且默认对齐方式为居中。红、蓝容器高度小于绿色容器,因此它们会在IndexedStack内部居中显示,自然无法贴紧黄色容器的底部。
解决办法:
给IndexedStack添加alignment: Alignment.bottomCenter属性,让所有子组件对齐到IndexedStack的底部。由于IndexedStack本身已经通过Positioned的bottom:0属性贴紧了黄色容器的底部,红、蓝容器就能跟着实现与黄色容器底部的对齐。
修改后的核心代码片段
Positioned( bottom: 0, left: 0, right: 0, child: IndexedStack( alignment: Alignment.bottomCenter, // 新增这一行 index: _selectedIndex, children: <Widget>[ Container(height: 50, color: Colors.red), Container(height: 100, color: Colors.blue), Container(height: 300, color: Colors.green), ], ), )
完整修改后的代码
import 'package:flutter/material.dart'; class Istack extends StatefulWidget { @override _IstackState createState() => _IstackState(); } class _IstackState extends State<Istack> { int _selectedIndex = 0; void _showContainer(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( body: Container( height: 600, child: Column( children: [ const SizedBox(height: 50), ElevatedButton( onPressed: () => _showContainer(0), child: const Text('Show Container 1'), ), ElevatedButton( onPressed: () => _showContainer(1), child: const Text('Show Container 2'), ), ElevatedButton( onPressed: () => _showContainer(2), child: const Text('Show Container 3'), ), Container( color: Colors.yellow, height: 400, child: Stack( children: [ Positioned( top: 0, child: Container( color: Color.fromARGB(255, 222, 136, 136), height: 200, ), ), Positioned( bottom: 0, left: 0, right: 0, child: IndexedStack( alignment: Alignment.bottomCenter, // 关键修改点 index: _selectedIndex, children: <Widget>[ Container(height: 50, color: Colors.red), Container(height: 100, color: Colors.blue), Container(height: 300, color: Colors.green), ], ), ), ], ), ), ], ), ), ); } }
内容的提问来源于stack exchange,提问作者Pannam
相关产品推荐
相关产品推荐

