どうも、ちょげ(@chogetarou)です。
BottomNavigationBarの有効と無効を切り替える方法を紹介します。
方法

BottomNavigationBarの有効と無効を切り替えるには、Bool型の変数と三項演算子を使います。
まず、Bool型の変数を用意します。
var _isDisabled = false;
そして、BottomNavigationBarの引数「onTap」に変数と三項演算子を使い、無効の時はnull、有効の時は関数が指定されるようにします。
BottomNavigationBar(
items: [
・・・
],
currentIndex: _currentIndex,
onTap: _isDisabled
? null
: (int index) {},
),
あとは、三項演算子に使っているBool型の変数の値をボタンなどで切り替えるだけです。
これでBottomNavigationBarの有効と無効を切り替えることが出来ます。
使用例
以下は、使用例です。
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var _isDisabled = false;
var _currentIndex = 1;
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: [
Container(
child: Text('Settings'),
alignment: Alignment.center,
color: Colors.green[100],
),
Container(
child: TextButton(
onPressed: () {
setState(() {
_isDisabled = !_isDisabled;
});
},
child: Text('Swicth'),
),
alignment: Alignment.center,
),
Container(
child: Text('Favorite'),
alignment: Alignment.center,
color: Colors.red[100],
),
],
),
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: _isDisabled
? null
: (int index) {
setState(() {
_currentIndex = index;
});
},
),
);
}
}
まとめ
BottomNavigationBarの有効と無効を切り替えるには、変数と三項演算子を使います。
コメント