flutter提供的tabbar已經(jīng)很完善了七问,如果想要自定義有兩種方法
1.Stack組件放在屏幕下面(需要自己適配iphoneX類的機型)
2.BottomAppBar和PageView的組合使用
注:兩者都有一個按鈕閃爍的問題:首次加載依次點擊時圖片會先消失然后再顯示選中狀態(tài)的圖片(只在使用本地的image時出現(xiàn))(可以錄屏一幀幀查看)
本文推薦使用2的方法宁舰,方法1主要適用于非常規(guī)的tabbar
使用Stack+Offstage組件防止首次切換時的閃爍
本地圖片的加載就不在這里贅述了
使用了插件flutter_screenutil: ^1.0.2
參考鏈接
https://www.cnblogs.com/qqcc1388/p/11799035.html
非常規(guī)的tabbar: http://www.reibang.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 = ['首頁', '通知', '學(xué)情分析', '我的'];
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(
//可以設(shè)置背景
// 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