[Flutter]BottomNavigationBarItemをタップした時の処理をするには?

Flutter

どうも、ちょげ(@chogetarou)です。

BottomNavigationBarItemをタップした時の処理をする方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

BottomNavigationBarItemをタップした時の処理をするには、BottomNavigationBarの引数「onTap」を使います。

まず、BottomNavigationBarの引数「onTap」に「(int index){}」のような関数を指定します。

関数の引数は、タップされたBottomNavigationBarItemのインデックスを取得します。

そして、関数内の処理で、タップした時の処理を指定します。

BottomNavigationBar(
  onTap: (int index){/*タップ処理*/},
  items: [
    ・・・
  ],
  currentIndex: _currentIndex,
),

これでBottomNavigationBarItemをタップした時の処理を設定できます。

使用例

以下は、使用例です。

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  var _currentIndex = 0;

  var _pages = <Widget>[
    Center(
      child: Text('Settings'),
    ),
    Container(
      child: Text('Home'),
      alignment: Alignment.center,
      color: Colors.blue,
    ),
    Container(
      child: Text('Share'),
      alignment: Alignment.center,
      color: Colors.pink.withOpacity(0.3),
    ),
  ];

  void _onTap(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      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,
      ),
    );
  }

まとめ

BottomNavigationBarItemをタップした時の処理をするには、BottomNavigationBarの引数「onTap」を使います。

コメント

タイトルとURLをコピーしました