🎯

[Flutter] BottomNavigationBar and AppBar

2022/06/13に公開

公式

AppBar

https://api.flutter.dev/flutter/material/AppBar-class.html

BottomNavigationBar

https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html

概要

BottomNavigationBarItemが選択された際に、AppBarTitleも同時に変更する
※状態管理としてGetXを使用(単純状態管理のみ使用(本内容とは別となるため説明は割愛とする))

main.dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  final controller = Get.put(MainController());
  
    return MaterialApp(
      home: GetBuilder<RootController>(
        builder: (context) {
            return Scaffold(
              appBar: AppBar(
                title: Text(controller.appBarTitle.title ?? ""),
                backgroundColor: Colors.black87,
              ),
              bottomNavigationBar: tabView(controller),
              body: MainEntity.pages[controller.selectIndex],
           );
        }
     );
  }
}

  Widget tabView(RootController controller) {
    return BottomNavigationBar(
      currentIndex: controller.selectIndex,
      type: BottomNavigationBarType.fixed,
      backgroundColor: Colors.black87,
      fixedColor: Colors.redAccent,
      unselectedItemColor: Colors.white54,
      items: [
        BottomNavigationBarItem(
          icon: Icon(Icons.settings),
          label: 'first',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.library_add),
          label: 'second',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.search),
          label: 'third',
        ),
      ],
      onTap: controller.increment,
    );
  }
main_controller.dart

enum AppBarTitle { first, second, third }

class MainController extends GetxController {

  int selectIndex = 0;

  AppBarTitle appBarTitle = AppBarTitle.first;

  increment(int index) {
    selectIndex = index;
    appBarTitle = AppBarTitle.values[index];
    update();
  }
}

extension AppBarTitleExtension on AppBarTitle {
  static final names = {
    AppBarTitle.first: "First",
    AppBarTitle.second: "Second",
    AppBarTitle.third: "Third"
  };

  String? get title => names[this];
}
main_entity.dart

class MainEntity {

  static final pages = [FirstView(), secondView(), thirdView()];
}

※今回はMainファイル内にて完結していますが、部品ごとにWidgetを分割するのも良いですし、状態管理もRiverPodなどを使用してglobalにアクセスできる方が可読性が上がるかもしれませんね。

Discussion