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 {...