Flutter - 实现底部导航栏

效果图:

 

代码如下:

import 'package:flutter/material.dart';

class BottomTabBarWidget extends StatefulWidget {

  final Color backgroundColor;

  final Color indicatorColor;

  final List<Widget> tabItems;

  final List<Widget> pageViews;

  final PageController pageController;

  BottomTabBarWidget(this.backgroundColor, this.indicatorColor, this.tabItems,
      this.pageViews, this.pageController);
  @override
  _BottomTabBarWidgetState createState() => _BottomTabBarWidgetState(
      this.backgroundColor,
      this.indicatorColor,
      this.tabItems,
      this.pageViews,
      this.pageController);
}

class _BottomTabBarWidgetState extends State<BottomTabBarWidget>
    with SingleTickerProviderStateMixin {  ///实现 SingleTickerProviderStateMixin 该接口的目的是防止每次滑动都重新绘制页面

  Color _backgroundColor;

  Color _indicatorColor;

  List<Widget> _tabItems;

  List<Widget> _pageViews;

  _BottomTabBarWidgetState(this._backgroundColor, this._indicatorColor,
      this._tabItems, this._pageViews, this._pageController)
      : super();

  TabController _tabController;

  PageController _pageController;

  @override
  void initState() {
    super.initState();

    ///初始化时创建控制器
    ///通过 with SingleTickerProviderStateMixin 实现动画效果。
    _tabController = new TabController(vsync: this, length: _tabItems.length);
  }

  @override
  void dispose() {
    ///页面销毁时,销毁控制器
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: PageView(
          controller: _pageController,
          children: _pageViews,
          onPageChanged: (index) {
            _tabController.animateTo(index); /// 滑动跳转(即左右滑动)(点击跳转需外部实现)
          },
        ),
        bottomNavigationBar: Material(
          color: _backgroundColor,

          ///tabBar控件
          child: new TabBar(
            ///必须有的控制器,与pageView的控制器同步
            controller: _tabController,

            ///每一个tab item,是一个List<Widget>
            tabs: _tabItems,

            ///tab底部选中条颜色
            indicatorColor: _indicatorColor,
          ),
        ));
  }
}

点击跳转实现(比如从第一页直接跳转到第三页),在每一个TabBar 的 Item 的 onPress 属性中编写如下代码:

onPressed: () {
                  pageController.jumpTo(MediaQuery.of(context).size.width * 1);
                },

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值