首页
/ AutoRoute 库中实现带悬浮按钮的底部导航栏方案

AutoRoute 库中实现带悬浮按钮的底部导航栏方案

2025-07-09 19:45:54作者:贡沫苏Truman

背景介绍

在 Flutter 应用开发中,底部导航栏结合中央悬浮按钮(FAB)是一种常见的 UI 设计模式。当使用 AutoRoute 路由库时,开发者可能会遇到如何正确实现这种布局的技术挑战。

标准实现方式

在原生 Flutter 中,我们可以通过 IndexedStackBottomAppBar 的组合轻松实现这种布局:

IndexedStack(
  index: currentIndex(),
  children: const [
    AScreen(),
    CScreen(),
  ],
),
floatingActionButton: FloatingActionButton(
  onPressed: () {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => const BScreen()),
    );
  },
),
bottomNavigationBar: BottomAppBar(
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: [
      IconButton(onPressed: () => setCurrentIndex(0), icon: Icon(Icons.a)),
      SizedBox(width: 32),
      IconButton(onPressed: () => setCurrentIndex(1), icon: Icon(Icons.b)),
    ],
  ),
)

AutoRoute 中的实现方案

在 AutoRoute 中,由于路由管理的特殊性,我们需要采用不同的实现方式。以下是两种可行的解决方案:

方案一:使用 AutoTabsRouter 手动控制索引

AutoTabsRouter(
  routes: const [
    ARoute(),
    BRoute(),
    CRoute(),
  ],
  builder: (context, child) {
    final tabsRouter = AutoTabsRouter.of(context);
    
    return Scaffold(
      body: child,
      floatingActionButton: FloatingActionButton(
        onPressed: () => tabsRouter.setActiveIndex(1),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          children: [
            IconButton(
              onPressed: () => tabsRouter.setActiveIndex(0),
              icon: Icon(Icons.a)
            ),
            SizedBox(width: 48),
            IconButton(
              onPressed: () => tabsRouter.setActiveIndex(2),
              icon: Icon(Icons.settings)
            ),
          ],
        ),
      ),
    );
  },
)

方案二:使用根路由替代标签路由

AutoRoute 作者建议的另一种方案是将 FAB 触发的路由作为根路由而非标签路由。这种方式可以简化实现逻辑,特别是当不需要在 FAB 路由中显示底部导航栏时更为适用。

技术要点解析

  1. 路由索引控制:在 AutoRoute 中,必须通过 tabsRouter.setActiveIndex 显式控制路由切换,直接使用导航方法可能无效。

  2. 布局适配:底部导航栏需要为 FAB 留出空间,通常使用 BottomAppBarCircularNotchedRectangle 形状。

  3. 状态管理:路由索引状态应由 AutoRoute 的 tabsRouter 管理,而非自行维护状态变量。

  4. 视觉平衡:在底部导航栏中,需要为 FAB 预留适当的空间(如 SizedBox),以保持 UI 的对称性。

最佳实践建议

  1. 如果 FAB 路由需要保持底部导航栏可见,推荐使用方案一。

  2. 如果 FAB 路由是全屏内容,不需要底部导航栏,则采用方案二更为简洁。

  3. 对于复杂的路由场景,可以考虑结合使用 AutoRoute 的嵌套路由功能。

通过以上方案,开发者可以在 AutoRoute 中灵活实现带中央悬浮按钮的底部导航栏布局,满足各种应用场景的需求。

登录后查看全文
热门项目推荐
相关项目推荐