flutter提供的tabbar已经很完善了,如果想要自定义有两种方法
1.Stack组件放在屏幕下面(需要自己适配iphoneX类的机型)
2.BottomAppBar和PageView的组合使用
注:两者都有一个按钮闪烁的问题:首次加载依次点击时图片会先消失然后再显示选中状态的图片(只在使用本地的image时出现)(可以录屏一帧帧查看)
本文推荐使用2的方法,方法1主要适用于非常规的tabbar
使用Stack+Offstage组件防止首次切换时的闪烁
本地图片的加载就不在这里赘述了
使用了插件flutter_screenutil: ^1.0.2
参考链接
https://www.cnblogs.com/qqcc1388/p/11799035.html
非常规的tabbar: https://www.jianshu.com/p/e9f408cfd3ce- 如果有更好的解决切换图片闪烁问题望告知
import 'package:flutter/material.dart';
import 'package:custom_tabbar_demo/pages/home_page.dart';
import 'package:custom_tabbar_demo/pages/message_page.dart';
import 'package:custom_tabbar_demo/pages/study_page.dart';
import 'package:custom_tabbar_demo/pages/mine_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class PageViewTabbarPage extends StatefulWidget {
@override
_PageViewTabbarPageState createState() => _PageViewTabbarPageState();
}
class _PageViewTabbarPageState extends State<PageViewTabbarPage> {
PageController _pageController;
List images = [
['images/home_no.png', 'images/home_pr.png'],
['images/tongzhi_no.png', 'images/tongzhi_pr.png'],
['images/xueqing_no.png', 'images/xueqing_pr.png'],
['images/mine_no.png', 'images/mine_pr.png'],
];
final List _titles = ['首页', '通知', '学情分析', '我的'];
final List<Widget> _tabBodies = [
HomePage(),
MessagePage(),
StudyPage(),
MinePage(),
];
int _currentIndex = 0;
void initState() {
super.initState();
this._pageController =
PageController(initialPage: _currentIndex, keepPage: true);
}
BottomAppBar _bottomAppBar() {
return BottomAppBar(
child: Container(
//可以设置背景
// decoration: BoxDecoration(
// image: DecorationImage(
// fit: BoxFit.cover,
// repeat: ImageRepeat.noRepeat,
// image: AssetImage('images/shengyukeshibg.png'),
// ),
// ),
height: ScreenUtil().setHeight(98),
child: Row(
children: _customItems(),
),
),
);
}
List<Widget> _customItems() {
return images.map((img) {
int index = images.indexOf(img);
return InkWell(
onTap: () {
setState(() {
_currentIndex = index;
_pageController.jumpToPage(index);
});
},
child: Container(
color: Colors.white, //禁止水波效果
width: ScreenUtil().setWidth(750 / 4),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Stack(
children: <Widget>[
Offstage(
offstage: false,
child: Image.asset(img[0]),
),
Offstage(
offstage: _currentIndex == index ? false : true,
child: Image.asset(img[1]),
),
],
),
Text(
_titles[index],
style: TextStyle(
fontSize: ScreenUtil().setSp(24),
color: index == _currentIndex ? Colors.blue : Colors.black),
)
],
),
),
);
}).toList();
}
@override
Widget build(BuildContext context) {
ScreenUtil.init(context, width: 750, height: 1334);
return Scaffold(
appBar: AppBar(
title: Text('自定义tabbar'),
),
body: PageView(
physics: NeverScrollableScrollPhysics(),//禁止左右滑动
children: _tabBodies,
controller: _pageController,
),
bottomNavigationBar: _bottomAppBar(),
);
}
}
demo下载链接:https://github.com/FonChY/flutter_custom_tabbarDemo