どうも、ちょげ(@chogetarou)です。
IndexedStackを使って、BottomNavigationBarを実装する方法を紹介します。
方法

まず、選択中のインデックスを格納する変数とインデックスを更新する関数を用意します。
var _currentIndex = 0;//選択中のインデックスを格納する変数
void _onTap(int index) {
setState(() {
_currentIndex = index; //インデックスの更新
});
}
次に、Scaffoldの引数「bottomNavigationBar」にBottomNavigationBarを指定します。
そして、BottomNavigationBarの必要な引数の指定を行います。
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: [
//タブ
BottomNavigationBarItem(
icon: /*アイコン*/,
label: 'ラベル',
),
BottomNavigationBarItem(
icon: /*アイコン*/,
label: 'ラベル',
),
BottomNavigationBarItem(
icon: /*アイコン*/,
label: 'ラベル',
),
~~~ページの数だけ~~~
],
currentIndex: _currentIndex, //選択中のインデックス
onTap: _onTap, //インデックスの更新処理
),
);
}
最後に、Scaffoldの引数「body」にIndexedStackを指定します。
IndexedStackには、引数「index」に選択中のインデックス、引数「children」に表示するページをリストで指定します。
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex, //選択中のインデックス
children: [
//ページ
Page1(),
Page2(),
Page3(),
~~~省略~~~
],
),
bottomNavigationBar: BottomNavigationBar(
items: [
//タブ
BottomNavigationBarItem(
icon: /*アイコン*/,
label: 'ラベル',
),
BottomNavigationBarItem(
icon: /*アイコン*/,
label: 'ラベル',
),
BottomNavigationBarItem(
icon: /*アイコン*/,
label: 'ラベル',
),
~~~ページの数だけ~~~
],
currentIndex: _currentIndex,
onTap: _onTap,
),
);
}
これでIndexedStackを使ってBottomNavigationBarを実装することが出来ます。
ポイントとしては、IndexedStackの引数「children」内のページとBottomNavigationBarの引数「items」内のタブを合わせる点です。
使用例
以下は、使用例です。
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var _currentIndex = 0;
void _onTap(int index) {
setState(() {
_currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: [
Container(
child: Text('Settings'),
alignment: Alignment.center,
color: Colors.lightGreen,
),
Container(
child: Text('Home'),
alignment: Alignment.center,
color: Colors.lightBlue,
),
Container(
child: Text('Favorite'),
alignment: Alignment.center,
color: Colors.pink.withOpacity(0.5),
),
],
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
label: 'Favorite',
),
],
currentIndex: _currentIndex,
onTap: _onTap,
),
);
}
}

[Flutter]BottomNavigationBarItemの使い方
BottomNavigationBarItemの使い方を解説します。

[Flutter]BottomNavigationBarのエラーを解決する方法
BottomNavigationBarで発生したエラーを解決する方法を紹介します。

[Flutter]BottomNavigationBarの上にFloatingActionButtonを表示するには?
FloatingActionButtonは、デフォルトでは、BottomNavigationBarと重なってしまいます。これを回避して、BottomNavigationBarの上に、FloatingActionButtonを表示する方法を紹介します。
コメント