どうも、ちょげ(@chogetarou)です。
BottomNavigationBarによって選択されたページによって、AppBarのタイトルを変える方法を紹介します。
方法

BottomNavigationBarのitemによってAppBarのタイトルを変えるには、まずタイトル用の変数を用意します。
var _title = 'Your title';
次に、AppBarの引数「title」に用意した変数を指定します。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_title),
),
);
}
最後に、BottomNavigationBarのタップ処理に変更を加えます。
タップされたBottomNavigationBarItemのインデックスによって、switch文でタイトルが変わるようにします。
void _onTap(int index) {
setState(() {
_currentIndex = index;//インデックスの更新
//タイトルの更新
switch (index) {
case 0:
_title = 'インデックス0のタイトル';
break;
case 1:
_title = 'インデックス1のタイトル';
break;
case 2:
_title = 'インデックス2のタイトル';
break;
・・・
}
});
}
あとは、BottomNavigationBarの引数「onTap」にタップ処理を指定します。
これでBottomNavigationBarのitemによってAppBarのタイトルを変えることが出来ます。
使用例
以下は、使用例です。
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var _title = 'Home';
var _currentIndex = 1;
var _pages = [
Container(
child: Text('Settings'),
alignment: Alignment.center,
color: Colors.green,
),
Container(
child: Text('Home'),
alignment: Alignment.center,
color: Colors.yellow,
),
Container(
child: Text('Favorite'),
alignment: Alignment.center,
color: Colors.pink.withOpacity(0.3),
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_title),
),
body: _pages[_currentIndex],
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,
),
);
}
void _onTap(int index) {
setState(() {
_currentIndex = index;
switch (index) {
case 0:
_title = 'Settings';
break;
case 1:
_title = 'Home';
break;
case 2:
_title = 'Favorite';
break;
}
});
}
}
まとめ
BottomNavigationBarのitemによってAppBarのタイトルを変えるには、変数とBottomNavigationBarのタップ処理を使います。
コメント