【问题标题】:Changing the Bottom Navigation Bar when switching between screens in the body of a Scaffold在 Scaffold 主体中的屏幕之间切换时更改底部导航栏
【发布时间】:2025-12-08 10:50:01
【问题描述】:

HomeScreen() 函数调用 App 的主屏幕。 如何在没有 BottomNavigationBar 和 AppBar 的情况下路由/移动到“团队”、“添加”等页面。 我想用新的底部导航栏显示另一个页面和返回按钮。

我的 Flutter 项目中有这个:

class APPMain extends StatefulWidget {
  @override
  _APPMainState createState() => _APPMainState();
}

class _APPMainState extends State<APPMain> {

  int _currentIndex = 0;

  _onTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> screens = [
      HomeScreen(),
      Center(child: Text("Team")),
      Center(child: Text("Add")),
      Center(child: Text("Search")),
      Center(child: Text("Settings")),
    ];

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xffffffff),
        iconTheme: IconThemeData(color: Colors.grey),
        title: Text("Test App", style: TextStyle(color: Colors.grey),),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.account_circle),
            onPressed: (){},
          ),
        ],
      ),
      body: Container(
          color: Color(0xfff4f4f4),
          child: Center(
            child: screens[_currentIndex],
          ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        fixedColor: Colors.red,
        onTap: _onTapped,
        items: [
            BottomNavigationBarItem(
              title: Text('Home'), icon: Icon(Icons.home)),
            BottomNavigationBarItem(
              title: Text('Team'), icon: Icon(Icons.group)),
            BottomNavigationBarItem(
              title: Text('Add'), icon: Icon(Icons.add)),
            BottomNavigationBarItem(
              title: Text('Search'), icon: Icon(Icons.search)),
            BottomNavigationBarItem(
              title: Text('Settings'), icon: Icon(Icons.settings)),
          ]),
      );
  }
}

非常感谢您的帮助。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    这几乎可以肯定是重复的,但我无法通过快速搜索找到类似问题的问题,所以无论如何我都会回答。

    答案实际上很简单,但需要更多地了解如何编写 Flutter 应用程序 - 您应该使用 Navigator 或 MaterialApp 或 WidgetApp 中内置的导航器,而不是自己制作导航。最简单的方法是使用 MaterialApp 的 routes 属性并在每个页面中传递一个地图。然后,当您要切换页面时,只需在要切换页面的任何位置(即按钮)使用Navigator.pushNamed(context, &lt;name&gt;)

    当您来自其他框架时,可能会稍微令人困惑的部分是,与其拥有一个 Scaffold 并切换它的主体,整个页面应该切换并且每个页面都应该有一个 Scaffold。

    Here's an example in the documentation 显示如何在页面之间导航。

    作为记录,虽然这是一个坏主意,但您也可以使其与您的原始代码一起使用 - 您所要做的就是根据 _currentIndex 的设置构建一个具有不同选项的不同 BottomNavigationBar。但我不建议这样做。根据我的建议,您还可以获得页面之间的动画、后退按钮功能、您可以连接分析以跟踪页面使用情况,以及 Flutter 作为导航的一部分提供的更多内容。

    【讨论】: