【Flutter】タブのページをスワイプで切り替える方法

Flutter

タブのページをスワイプで切り替える方法を紹介します!

前提

タブでページを切り替えられるようになっていることが前提です。
タブでのページ切り替えについては、以下の記事で紹介していますのでご参照ください。

方法

スワイプでページ切り替えを行うには、PageView を使用します。
タブでページ切り替えの実装例から以下のソースコードのように変更します。

主な変更点

  • PageController のインスタンスを生成(10行目)
  • Scaffold の body に PageView を設定(26〜34行目)
  • タブのアイテムがタップされたときに PageController で page を切り替えるよう指定(47行目)
class BottomTabBarSample extends StatefulWidget {
  const BottomTabBarSample({Key? key}) : super(key: key);

  @override
  State<BottomTabBarSample> createState() => _BottomTabBarSampleState();
}

class _BottomTabBarSampleState extends State<BottomTabBarSample> {

  final _pageController = PageController();

  int _currentIndex = 0;
  final _pages = [
    const TabSamplePage('Home'),
    const TabSamplePage('Chat'),
    const TabSamplePage('Search'),
    const TabSamplePage('Settings')
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Bottom Tab Bar Sample"),
      ),
      body: PageView(
        controller: _pageController,
        children: _pages,
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(icon: Icon(Icons.chat), label: 'Chat'),
          BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
          BottomNavigationBarItem(icon: Icon(Icons.settings), label: 'Settings'),
        ],
        currentIndex: _currentIndex,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
          _pageController.jumpToPage(index);
        },
        selectedItemColor: Colors.white,
        unselectedItemColor: Colors.white54,
        backgroundColor: Colors.blue,
        type: BottomNavigationBarType.fixed,
      ),
    );
  }
}

まとめ

タブのページをスワイプで切り替える方法を紹介しました!

  • PageView を使用することで、スワイプによるタブ切り替えが可能
    • PageController のインスタンスを生成し、body に PageView を指定
    • タブアイテムのタップ時に、PageController でページを切り替えるよう指定

以上で、【Flutter】タブのページをスワイプで切り替える方法 は終わりです。

参考

おすすめ書籍

コメント

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