Flutter中如何将Container堆叠在另一Container内部或正下方
问题根因
- 你将两个独立的
Stack放在Column中布局,第二个Stack没有指定宽高,而Positioned组件仅在有明确尺寸的Stack内部生效,无尺寸的Stack无法正确计算Positioned的偏移量,导致灰色Container无法按预期显示。 - 你要实现的是「灰色Container部分叠在红色弧形Container下方、剩余部分外露」的效果,不需要拆分两个Stack,把两个Container都放在同一个Stack里即可。
修复后的完整代码
import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp(home: MainScreen())); } class MainScreen extends StatelessWidget { const MainScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; return Scaffold( body: Stack( // 所有元素都放在同一个Stack内 children: [ // 第一层:红色弧形Container Container( height: 250.0, width: width, decoration: const BoxDecoration( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(150), bottomRight: Radius.circular(150), ), color: Colors.redAccent, ), child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const <Widget>[ Text( "Hello World", style: TextStyle( fontSize: 22, fontFamily: "Arial", fontWeight: FontWeight.bold, color: Colors.white), ), Text( "Hello World", style: TextStyle( fontSize: 22, fontFamily: "Arial", fontWeight: FontWeight.bold, color: Colors.white), ), ], ), ), ), // 第二层:灰色Container,top设为220刚好部分叠在红色Container底部下方 Positioned( top: 220, left: 20, child: Container( height: 500, width: 200, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.grey, ), ), ), ], ), ); } }
效果说明
- 灰色Container的
top值设置为220,刚好和高度为250的红色Container底部有30px的重叠,既实现了堆叠效果,两个Container的底部也不会产生多余重叠。 - 所有元素放在同一个Stack内,不需要嵌套多层Stack/Column,布局逻辑更清晰,Positioned的偏移计算也不会出现异常。
内容的提问来源于stack exchange,提问作者Baasith Fazil
相关产品推荐
相关产品推荐

