どうも、ちょげ(@chogetarou)です。
BottomNavigationBarでPageViewを使う方法を紹介します。
方法

まず、PageControllerの変数と最新のページを格納する変数を用意します。
var _controller = PageController();
var _currentIndex = 1; //最新のページのインデックス
次に、Scaffoldの引数「body」にPageViewを指定します。
PageViewの引数「controller」に用意したPageControllerの変数、引数「pages」に表示するページをリストで指定します。
また、引数「pageChanged」で、最新のページを更新する処理を指定します。
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _controller,
children: _pages,
onPageChanged: (index) {
setState(() {
_currentIndex = index;
});
},
),
);
}
次に、Scaffoldの引数「bottomNavigationBar」にBottomNavigationBarを指定し、必要な引数の指定をします。
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
・・・
),
bottomNavigationBar: BottomNavigationBar(
items: [
~~~タブ~~~
],
currentIndex: _currentIndex, //最新のページの変数を指定
),
);
}
最後に、BottomNavigationBarの引数「onTap」に関数を指定します。
関数では、変数の更新とPageViewのページの更新をします。
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
・・・
),
bottomNavigationBar: BottomNavigationBar(
items: [
・・・
],
currentIndex: _currentIndex,
onTap: (int index) {
setState(() {
_currentIndex = index;//変数の更新
});
_controller.jumpToPage(index); //PageViewのページの更新
},
),
);
}
これでBottomNavigationBarでPageViewが使えるようになります。
使用例
以下は、使用例です。
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var _controller = PageController(initialPage: 1);
var _currentIndex = 1;
var _pages = [
Container(
child: Text('Settings'),
alignment: Alignment.center,
color: Colors.blue[100],
),
Container(
child: Text('Home'),
alignment: Alignment.center,
),
Container(
child: Text('Favorite'),
alignment: Alignment.center,
color: Colors.blue[100],
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _controller,
children: _pages,
onPageChanged: (index) {
setState(() {
_currentIndex = index;
});
},
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.yellow[200],
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: (int index) {
setState(() {
_currentIndex = index;
});
_controller.jumpToPage(index);
},
),
);
}
}
まとめ
BottomNavigationBarでPageViewを使うには、PageViewとBottomNavigationBarのそれぞれでページが更新されるようにします。
コメント