🦦

routemasterでのbottomNavigationBar(material)で実装してみた。

2022/01/24に公開

当初はauto_routeでの実装を検討していたが、使用時にtabviewで躓いた(私だけのお話)のでroutemasterに乗り換えた際のお話。

そもそもの選定基準

・公式がわかりやすい
・tabviewでも使用可能
・bottomNavigationBarでも使用可能。

乗り換えている途中に問題発生。

公式にはbottomNavigationBarがCupertinoの仕様になっていた。
https://pub.dev/packages/routemaster

routemaster: ^0.9.5

Setup:

RouteMap(
  routes: {
    '/': (route) => CupertinoTabPage(
          child: HomePage(),
          paths: ['/feed', '/settings'],
        ),
    '/feed': (route) => MaterialPage(child: FeedPage()),
    '/settings': (route) => MaterialPage(child: SettingsPage()),
  },
)

Main page:

class HomePage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    final tabState = CupertinoTabPage.of(context);

    return CupertinoTabScaffold(
      controller: tabState.controller,
      tabBuilder: tabState.tabBuilder,
      tabBar: CupertinoTabBar(
        items: [
          BottomNavigationBarItem(
            label: 'Feed',
            icon: Icon(CupertinoIcons.list_bullet),
          ),
          BottomNavigationBarItem(
            label: 'Settings',
            icon: Icon(CupertinoIcons.search),
          ),
        ],
      ),
    );
  }
}


問題発生、FloatingActionButtonを使用時

bottomNavigationBar呼び出すwidget‥screen内でのFloatingActionButtonを実装。
※bottomNavigationBar呼び出すところでFloatingActionButton実装してもこうなる。

そもそもCupertinoを使用することを検討していなかったので公式には掲載されていなかったがどうにかできるかやってみた。

Main page:


  int _currentIndex = 0;
    
  Widget build(BuildContext context) {
    final tabState = CupertinoTabPage.of(context);

          return SafeArea(
            child: Scaffold(
	    //tabState.tabBuilder(context, _currentIndex)がwidget判定してくれた。 
              body: tabState.tabBuilder(context, _currentIndex),
	      bottomNavigationBar: BottomNavigationBar(
                currentIndex: _currentIndex,
                type: BottomNavigationBarType.fixed,
                selectedItemColor: Colors.red,
                items: [
                  const BottomNavigationBarItem(
                    icon: Icon(CupertinoIcons.list_bullet),
                    label: "Feed",
                  ),
                  const BottomNavigationBarItem(
                    icon: Icon(CupertinoIcons.search),
                    label: "Settings",
                  ),
                ],
                //indexは生成するリストアイテムのインデックスです。
                onTap: (index) {
                  setState(() {
                    _currentIndex = index;
                    tabState.tabBuilder(context, _currentIndex);
                  });
                },
              ),
            ),
          );

とりあえず、上記で実装ができました。
tabState.tabBuilderに辿り着くまでに結構時間食った。
誰かのお役に立てれば幸いです。

Discussion