[Flutter]BottomNavigationBarを使って画面遷移する方法

Flutter

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

BottomNavigationBarを使って画面遷移する方法を紹介します。

スポンサーリンク

方法

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

BottomNavigationBarを使って画面遷移するには、Scaffoldの引数「bottomNavigationBar」を使います。

まず、選択中のインデックスを格納する変数と遷移するページのリストを用意します。

  var _selectIndex = 0;
  
  var _pages = <Widget>[
    Page1(),
    Page2(),
    Page3(),
    ~省略~
  ];

次に、BottomNavigationBarがタップされた時に、選択中のインデックスを変更する関数を用意します。

  void _onTapItem(int index) {
    setState(() {
      _selectIndex = index; //インデックスの更新
    });
  }

そして、Scaffoldの引数「body」で、選択しているページがリストから表示されるようにします。

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: _pages[_selectIndex], //リストから選択されているページが表示される
  );
}

最後に、引数「bottomNavigationBar」にBottomNavigationBarを指定します。

BottomNavigationBarの引数「items」には、タブとして表示するアイコンとラベルをBottomNavigationBarItemで設定します。

また、引数「currentIndex」に選択中のインデックス、onTapに選択中のインデックスを変更する関数を指定します。

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: _pages[_selectIndex],
    bottomNavigationBar: BottomNavigationBar(
      items: [
       //タブ
        BottomNavigationBarItem(
          icon: /*タブのアイコン*/,
          label: 'ラベル',
        ),
        BottomNavigationBarItem(
          icon: /*タブのアイコン*/,
          label: 'ラベル',
        ),
        BottomNavigationBarItem(
          icon: /*タブのアイコン*/,
          label: 'ラベル',
        ),
        ~タブの数だけ用意~
      ],
      currentIndex: _selectIndex, //選択中のインデックス
      onTap: _onTapItem, //タップで選択中のインデックスを変更
    ),
  );
}

これでBottomNavigationBarを使って画面遷移することが出来ます。

使用例

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

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

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

  var _pages = <Widget>[
    Container(
      child: Text('Settings'),
      alignment: Alignment.center,
    ),
    Container(
      child: Text('Home'),
      alignment: Alignment.center,
      color: Colors.lightBlue,
    ),
    Container(
      child: Text('Favorite'),
      alignment: Alignment.center,
      color: Colors.pink.withOpacity(0.5),
    ),
  ];

  void _onTapItem(int index) {
    setState(() {
      _selectIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_selectIndex],
      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: _selectIndex,
        onTap: _onTapItem,
      ),
    );
  }
}

まとめ

BottomNavigationBarを使って画面遷移するには、Scaffoldの引数「bottomNavigationBar」を使います。

コメント

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