1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FlutterのBottomNavigationBarのテンプレコード

Last updated at Posted at 2021-08-17

FlutterのBottomNavigationBarのテンプレコード

公式ドキュメントの通りだが、
・BottomNavigationBarのためだけに、BottomNavigationBarのページをStatefulWidgetで作る、
・BottomNavigationBarのページのScaffoldにはbody、BottomNavigationBarの2つを書く、AppBarを各ページで切り替えたい場合はBottomNavigationBarのページではなく各ページに書く、AppBarを各ページで切り替えなくても良い時はBottomNavigationBarのページに書く、
・切り替え用の変数selectedIndex、List形式でpageListを作っておく、各ページへの変数の受け渡し方がわからないので、globalに変数を置いておくか、Provider等の状態管理方法を採用する、
・bodyには「pageList[selectedIndex]」を置き、selectedIndexの切り替えでページを切り替える、currentIndex、onTapは以下の通り、
・materialデザインには大量のアイコンが用意されている、デザインがビシッと決まるとカッコいいので日頃からどんなアイコンがあるか眺めておく、
https://api.flutter.dev/flutter/material/Icons-class.html
・上記の流れは後から変えるとやや面倒なのでBottomNavigationBarのレイアウトでアプリを作りたい場合は最初から作ること、

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int selectedIndex = 0;
  List<Widget> pageList = [
    TodoPage(),
    WeightPage(),
    MyPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pageList[selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(
              icon: Icon(Icons.check_box),
              label: '入力',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.multiline_chart),
            label: 'グラフ',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: '設定',
          ),
        ],
        currentIndex: selectedIndex,
        onTap: (int index) {
          setState(() {
            selectedIndex = index;
          });
        },
      ),
    );
  }
}

class TodoPage extends StatefulWidget {...
class WeightPage extends StatefulWidget {...
class MyPage extends StatefulWidget {...

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?