TabBar 分成 子页面和父页面,接口只请求一次
父页面
class TabBarPage extends StatefulWidget {
const TabBarPage({super.key});
@override
State<TabBarPage> createState() => _TabBarPageState();
}
class _TabBarPageState extends State<TabBarPage> with SingleTickerProviderStateMixin{
late TabController tabController ;
@override
void initState() {
super.initState();
tabController = TabController(length: 2, vsync: this, initialIndex: 0);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:null,
body: DefaultTabController(
length: 2,
child: Column(
children: [
TabBar(
controller: tabController,
tabs: const [
Tab(text: 'Page 1'),
Tab(text: 'Page 2'),
],
indicatorWeight: 3.rpx,
indicatorPadding: const EdgeInsets.all(0),
labelPadding: const EdgeInsets.all(0),
isScrollable: false,
indicatorSize: TabBarIndicatorSize.label,
indicatorColor: const Color(0xff1A71FF),
labelStyle: const TextStyle(fontWeight: FontWeight.w700),
labelColor: const Color(0xff1A71FF),
unselectedLabelColor: const Color(0xff2E3346),
unselectedLabelStyle:
const TextStyle(fontWeight: FontWeight.w500),
),
Expanded(
child: TabBarView(
controller: tabController,
children: [
TabBarWidget1(),
TabBarWidget2(),
],
))
],
)),
);
}
}
两个子页面,数据请求放进子页面来请求
class TabBarWidget1 extends StatefulWidget {
const TabBarWidget1({super.key});
@override
State<TabBarWidget1> createState() => _TabBarWidget1State();
}
class _TabBarWidget1State extends State<TabBarWidget1>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return ListView.builder(
shrinkWrap: true,
itemCount: 100,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: const EdgeInsets.all(4),
width: 100,
height: 20,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10)),
);
});
}
@override
bool get wantKeepAlive => true;
}
class TabBarWidget2 extends StatefulWidget {
const TabBarWidget2({super.key});
@override
State<TabBarWidget2> createState() => _TabBarWidget2State();
}
class _TabBarWidget2State extends State<TabBarWidget2>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return ListView.builder(
shrinkWrap: true,
itemCount: 100,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: const EdgeInsets.all(4),
width: 100,
height: 20,
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(10)),
);
});
}
@override
bool get wantKeepAlive => true;
}