[Flutter] BottomNavigationBar を使用したナビゲーションメニューの作成
FlutterのUIの勉強のために、
Amazonのアプリのような画面下部のナビゲーションメニューで
画面を切り替えるアプリを作成しました。

ContentPage クラスは
メニューの操作によって切り替えられるWidgetです。
引数によって渡されたアイコンと文字列を表示します。
class ContentPage extends StatelessWidget
{
final IconData icon;
final String title;
ContentPage({required this.icon, required this.title});
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Container(
width: 250,
height: 250,
child: Center(
child: Column(
children: <Widget>[
Icon(icon, size: 60.0,),
Text(
title
),
],
)
),
),
),
);
}
}
_MyHomePageState がメインの今回のメインです。
BottomNavigationBarに設定したボタンを押下することで
画面の表示が切り替わります。
class _MyHomePageState extends State<MyHomePage> {
// 選択したページのインデックス
int _selectedIndex = 0;
// 各ボタンに対応するページのリスト
List<Widget> _pageList = [
ContentPage(icon: Icons.home, title: 'Home'),
ContentPage(icon: Icons.person, title: 'MyPage'),
ContentPage(icon: Icons.shopping_cart, title: 'Cart'),
ContentPage(icon: Icons.menu, title: 'Setting')
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _pageList[_selectedIndex],
// ボディは、リストから選択されたインデックスのページを表示する
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
// typeが未指定だと、ボタンを4つ以上設定すると自動的にshiftingに設定されてしまう
items : const <BottomNavigationBarItem>[
// 画面下に表示するボタンアイテムの設定
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.person), title: Text('MyPage')),
BottomNavigationBarItem(icon: Icon(Icons.shopping_cart), title: Text('Cart')),
BottomNavigationBarItem(icon: Icon(Icons.menu), title: Text('Setting')),
],
currentIndex: _selectedIndex, // インデックスの初期値
onTap: _onTapped, // タップ時の処理
),
);
}
// タップ時の処理
void _onTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
}
コード上のコメントにも書いていますが、
“type”の指定を行わないと、BottomNavigationBar に4つ以上のアイテムを設定すると自動的に”type”が”shifting”になってしまうのが躓いたポイントです。
・・・・”type” に設定する” fixed “と”shifting “の違い・・・・
・BottomNavigationBarType.fixed :
ナビゲーションの各アイテムの横幅が固定
・BottomNavigationBarType.shifting :
選択状態のアイテムの幅が広がり、非選択状態のアイテムのラベルが非表示
水曜担当:Tanaka
tanaka at 2021年08月25日 10:00:00