Flutter TabbarController实现

MaterialApp风格实现

思路:PageView + BottomNavigationBar
PageView存放tabbar管理的子页面。
BottomNavigationBar负责tabbar展示及页面切换事件。

  • 创建StatefulWidget
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
  • 声明_pages和_barItems
/*页面索引*/
int _currentIndex = 0;

/*页面*/
List<Widget> _pages = [HomeView(),MyView()];

/*页面控制器*/
final _pageController = PageController();

/*tabbarItems*/
List<BottomNavigationBarItem> _barItems = [
  BottomNavigationBarItem(label: '首页', icon: Image.asset('images/tabbar_icon_house_normal.png'), activeIcon: Image.asset('images/tabbar_icon_house_selected.png')),
  BottomNavigationBarItem(label: '我的', icon: Image.asset('images/tabbar_icon_my_normal.png'), activeIcon: Image.asset('images/tabbar_icon_my_selected.png')),
];
  • 实现
/*声明_pages和_barItems*/
...
@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'my app',
    home: Scaffold(
      body: PageView.builder(
        physics: NeverScrollableScrollPhysics(),
        controller: _pageController,
        onPageChanged: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        itemBuilder: (context, index) {
          return _pages[index];
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: _barItems,
        currentIndex: _currentIndex,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.grey,
        selectedFontSize: 12,
        unselectedFontSize: 12,
        onTap: (int index) {
          _pageController.jumpToPage(index);
        },
      ),
    ),
  );
}
  • 清理
@override
void dispose() {
  super.dispose();
  _pageController.dispose();
}

实际使用时,应将此实现封装到一个dart文件中,方便维护。

效果


image.png

CupertinoApp风格实现

@override
Widget build(BuildContext context) {
  return CupertinoApp(
    title: 'my app',
    home: CupertinoTabScaffold(
        tabBar: CupertinoTabBar(
          items: _barItems,
          currentIndex: _currentIndex,
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
        tabBuilder: (context, index) {
          return _pages[index];
        },
      ),
    );
  }

对应的CupertinoPageScaffold页面

class HomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: Text('首页'),
      ),
      child: Container(
        child: Text('文本'),
      ),
    );
  }
}

效果


image.png

推荐阅读更多精彩内容