Flutter:跳转至Comment页面时如何隐藏BottomNavigationBar
问题分析
你当前的Comment页面是在mainscreen的Scaffold的body区域内跳转的,而mainscreen的Scaffold固定包含了bottomNavigationBar,所以跳转后的页面依然会显示底部导航栏。
解决方案
方法一:使用根导航器跳转(简单快捷)
在跳转Comment页面时,指定使用根导航器,让新页面加载在整个导航栈的最上层,直接覆盖原有的mainscreen(包括底部导航栏):
Navigator.of(context, rootNavigator: true).push( MaterialPageRoute( builder: (context) => comment( body: document['body'], title: document['title'], date: document['date'], ), ), );
方法二:重构页面结构(适合复杂导航场景)
将mainscreen的body改为独立的导航容器,专门管理home/draft/Profile三个页面的内部导航,外部页面(如Comment)则通过根导航器跳转,这种方式能更好地分离不同页面栈的状态:
修改mainscreen的实现代码:
class _mainscreenState extends State<mainscreen> { int _selectedIndex = 0; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( body: IndexedStack( index: _selectedIndex, children: [ Navigator( onGenerateRoute: (settings) => MaterialPageRoute( builder: (context) => home(), ), ), Navigator( onGenerateRoute: (settings) => MaterialPageRoute( builder: (context) => draft(), ), ), Navigator( onGenerateRoute: (settings) => MaterialPageRoute( builder: (context) => Profile(), ), ), ], ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.add_circle_outline_sharp), label: 'Create', ), BottomNavigationBarItem( icon: Icon(Icons.person), label: 'Profile', ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.amber[800], onTap: _onItemTapped, ), ); } }
跳转Comment页面时依然使用根导航器,写法同方法一。
方法三:临时覆盖(不推荐)
如果不想修改跳转逻辑,可在Comment页面的Scaffold中强制占满屏幕,覆盖底部导航栏,但这属于治标不治本的临时方案:
class comment extends StatelessWidget { final String body; final String title; final String date; const comment({super.key, required this.body, required this.title, required this.date}); @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, appBar: AppBar( // 你的页面导航栏配置 title: Text(title), ), body: SizedBox( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: // 你的页面内容 ), ); } }
推荐方案
优先选择方法一,改动最小且能直接解决问题;如果你的应用后续有更复杂的导航需求,再考虑使用方法二重构页面结构。
内容的提问来源于stack exchange,提问作者Devika
相关产品推荐
相关产品推荐

