Flutter中如何将bottomNavigationBar定位在屏幕顶部
Flutter 中 Scaffold 组件自带的 bottomNavigationBar 属性默认固定定位在页面底部,要实现顶部放置同款导航栏,可按以下两种方案操作:
方案1:嵌入AppBar的bottom区域(最推荐)
如果你的页面需要顶部标题栏,直接将导航组件放在AppBar的bottom参数中即可,示例代码如下:
Scaffold( appBar: AppBar( title: const Text('页面标题'), // 这里放置你的导航组件,支持直接用BottomNavigationBar bottom: PreferredSize( preferredSize: const Size.fromHeight(56), // 和默认BottomNavigationBar高度一致 child: BottomNavigationBar( // 你原来写在bottomNavigationBar里的配置完全不用改 currentIndex: _selectedIndex, onTap: _onItemTapped, items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'), BottomNavigationBarItem(icon: Icon(Icons.category), label: '分类'), BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'), ], ), ), ), body: const [HomePage(), CategoryPage(), MinePage()][_selectedIndex], )
方案2:直接在Body顶部放置
如果不需要默认的AppBar,直接用Column布局把导航组件放在最顶部即可:
Scaffold( body: Column( children: [ // 顶部直接放BottomNavigationBar BottomNavigationBar( currentIndex: _selectedIndex, onTap: _onItemTapped, items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'), BottomNavigationBarItem(icon: Icon(Icons.category), label: '分类'), BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'), ], ), // 页面内容区域用Expanded撑满剩余高度 Expanded( child: const [HomePage(), CategoryPage(), MinePage()][_selectedIndex], ) ], ), )
- 两种方案都不需要修改你原来写
bottomNavigationBar的逻辑代码,只需要调整组件的摆放位置即可 - 如果需要自定义导航栏样式,也可以直接替换上面代码里的
BottomNavigationBar为你自己封装的导航组件
内容的提问来源于stack exchange,提问作者Amr El-Baroudy
相关产品推荐
相关产品推荐

