丑话不多说,直接上代码,实现当前界面统一刷新的TAB切换
import ‘package:flutter/material.dart’;
import ‘package:te_guide/app/common/Adapt.dart’;
/*
- 定义tab 的title 和标识
*/
class NewsTab {
String text;
String tab;
NewsTab(this.text, this.tab);
}
/*
- 自定义tab 组件
*/
class TabBarWidget extends StatelessWidget {
List tabList;
TabBarWidget({this.tabList, this.currentTab, this.onSelectTab});
NewsTab currentTab;
ValueChanged onSelectTab; //这个参数比较关键,仔细理解下,省了setState()调用的环节
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: this.tabList.asMap().keys.map((item) {
return GestureDetector(
//手势监听控件,用于监听各种手势
child: Container(
width: Adapt.px(234),
height: Adapt.px(64),
alignment: Alignment.center,
decoration: new BoxDecoration(
color: _colorTabMatching(item: this.tabList[item]),
border: new Border.all(
color: Color(0xFF3E4152),
width: 0.0,
),
),
child: Text(
this.tabList[item].text,
style: TextStyle(
color: _colorTabText(item: this.tabList[item]),
fontSize: Adapt.px(28),
fontWeight: FontWeight.w500,
fontFamily: Adapt.pingFangSC_Medium,
),
),
),
onTap: () => onSelectTab(
this.tabList[item],
)
//onSelectTab函数的使用非常巧妙,
//相当于定义了一个接口,可操控当前控件以外的数据
);
}).toList());
}
//定义tab被选中和没被选中的颜色样式ext
Color _colorTabMatching({NewsTab item}) {
return currentTab == item ? Color(0xFF141E32) : Color(0xFFFFFFFF);
}
//定义tab被选中和没被选中的字体颜色
Color _colorTabText({NewsTab item}) {
return currentTab == item ? Color(0xFFFFFFFF) : Color(0xFF141E32);
}
}