Flutter Web项目中Stack组件顶层AppSidebar未正常显示如何解决
问题根因
- Stack组件的子元素渲染逻辑为先渲染的元素位于底层,后渲染的元素位于上层,你当前代码中先放置
AppSidebar再放置UbuntuBackground,背景图直接覆盖了侧边栏,导致看不到侧边栏。 - 你编写的
AppSidebar外层Container没有设置固定宽度,默认会撑满整个屏幕,即使调整组件顺序也会完全覆盖背景。
修正方案
- 调整
Stack内的子组件顺序,将背景组件放在最底层,侧边栏放在上层。 - 给
AppSidebar添加固定宽度,同时使用Align组件将侧边栏固定在屏幕左侧。
修正后的UbuntuHomepage代码:
class UbuntuHomepage extends StatefulWidget { UbuntuHomepage({Key? key}) : super(key: key); @override _UbuntuHomepageState createState() => _UbuntuHomepageState(); } class _UbuntuHomepageState extends State<UbuntuHomepage> { @override Widget build(BuildContext context) { return Stack( children: <Widget>[ // 底层放置背景 UbuntuBackground(), // 上层放置侧边栏,固定在屏幕左侧 Align( alignment: Alignment.centerLeft, child: AppSidebar(), ), ] ); } }
修正后的AppSidebar代码:
class AppSidebar extends StatelessWidget { const AppSidebar({Key? key}) : super(key: key); static Color sidebarColor = Color(0xff0D486E); @override Widget build(BuildContext context) { return Container( // 侧边栏固定宽度,可根据需求调整 width: 70, decoration: BoxDecoration( color: sidebarColor, ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: Colors.grey, ), child: SizedBox( height: 50, width: 50, ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: Colors.grey, ), child: SizedBox( height: 50, width: 50, ), ), ], ), ); } }
修改完成后重新编译即可看到侧边栏正常叠加在背景上层。
内容的提问来源于stack exchange,提问作者neil_ruaro
相关产品推荐
相关产品推荐

