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

BottomNavigationBarでDrawerを開くには、BottomAppBarを使います。
まず、Scaffoldのキーを用意します。
そして、Scaffoldの引数「key」に用意したキー、引数「drawer」にDrawerを指定します。
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
drawer: Drawer(),
);
}
次に、Scaffoldの引数「bottomNavigationBar」にBottomAppBarを指定し、BottomAppBarの引数「child」にRowウェジェットを指定します。
Rowウェジェットの引数「children」にタブを配置します。
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
drawer: Drawer(),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
//タブ
IconButton(
onPressed: () {
setState(() {
_currentIndex = 0;
});
},
icon: Icon(/*アイコン*/),
),
・・・
],
),
),
);
}
最後に、Rowの引数「children」の1番後ろにIconButtonを指定し、そのIconButtonでDrawerが開けるようにします。
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
・・・
IconButton(
onPressed: () {
_scaffoldKey.currentState!.openDrawer();//Drawerを開く
},
icon: Icon(Icons.menu),
),
],
),
),
);
}
これでBottomNavigationBarのタブでDrawerが開けるようになります。
使用例
以下は、使用例です。
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
var _currentIndex = 1;
var _pages = [
Container(
child: Text('Settings'),
alignment: Alignment.center,
color: Colors.blue[100],
),
Container(
child: Text('Home'),
alignment: Alignment.center,
color: Colors.green[100],
),
Container(
child: Text('Favorite'),
alignment: Alignment.center,
color: Colors.red[100],
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
drawer: Drawer(),
body: IndexedStack(
index: _currentIndex,
children: _pages,
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
onPressed: () {
setState(() {
_currentIndex = 0;
});
},
icon: Icon(
Icons.settings,
color: _currentIndex == 0 ? Colors.blue : Colors.grey,
),
),
IconButton(
onPressed: () {
setState(() {
_currentIndex = 1;
});
},
icon: Icon(
Icons.home,
color: _currentIndex == 1 ? Colors.blue : Colors.grey,
),
),
IconButton(
onPressed: () {
setState(() {
_currentIndex = 2;
});
},
icon: Icon(
Icons.favorite,
color: _currentIndex == 2 ? Colors.blue : Colors.grey,
),
),
IconButton(
onPressed: () {
_scaffoldKey.currentState!.openDrawer();
},
icon: Icon(Icons.menu),
),
],
),
),
);
}
}
まとめ
BottomNavigationBarのタブでDrawerを開くには、BottomAppBarを使います。
コメント