You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter点击BottomNavigationBar按钮时动态切换AppBar对应标题的实现问询

实现方案

该需求有非常简易的实现方式,仅需要对现有代码做4处调整即可:

1. 新增状态变量

在_HomePageState类中新增两个变量,分别记录当前选中的导航索引、以及导航栏对应的标题列表,注意标题顺序要和你底部导航的BottomNavigationBarItem、_screens页面列表的顺序完全对应:

class _HomePageState extends State<HomePage> {
  PageController _pageController = PageController();
  List<Widget> _screens = [
    QuotesPage(), ListViewPage(), CalendarViewPage(), GradeTrackerPage(), DiaryPage(), BoosterCommunityPage(),
  ];
  // 新增以下两个变量
  int _currentSelectedIndex = 0;
  final List<String> _navTitles = [
    'Home',
    'Task List',
    'Calendar View',
    'Grade Tracker',
    'Diary Page',
    'Booster Community',
  ];

2. 修改导航点击回调

在点击底部导航切换页面时,同步更新选中索引并触发UI重绘:

void _onItemsTapped(int selectedIndex) {
  _pageController.jumpToPage(selectedIndex);
  // 新增以下代码
  setState(() {
    _currentSelectedIndex = selectedIndex;
  });
}

如果后续你需要放开PageView的滑动限制(去掉NeverScrollableScrollPhysics配置),可以同步修改_onPageChanged方法,实现滑动切换页面时标题也同步更新:

void _onPageChanged(int index) {
  setState(() {
    _currentSelectedIndex = index;
  });
}

3. 绑定AppBar标题

直接在AppBar的title属性中读取对应索引的标题即可:

appBar: AppBar(
  centerTitle: true,
  title: Text(_navTitles[_currentSelectedIndex]),
),

4. 补全底部导航选中态

你的原有代码没有绑定底部导航的选中索引,补充后可以让底部导航的选中高亮效果正常显示:

bottomNavigationBar: BottomNavigationBar(
  onTap: _onItemsTapped,
  // 新增以下两行配置
  currentIndex: _currentSelectedIndex,
  selectedItemColor: Colors.orange, // 可自定义选中颜色
  items: [
    // 原有item配置保持不变
  ],
)

以上修改完成后即可实现点击底部导航时,AppBar标题和底部导航选中态同步更新的效果。

内容的提问来源于stack exchange,提问作者user14462150

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 23:15:03