使用 TabBar 和 TabBarView 結(jié)合展示數(shù)據(jù),當(dāng)頁(yè)面 A 切換到 B,然后從 B 切換回 A,這時(shí)候就會(huì)發(fā)現(xiàn) A 頁(yè)面的狀態(tài)又恢復(fù)到初始狀態(tài)了,這不是想要的結(jié)果,需要減少不必要的重繪,這時(shí)候就需要頁(yè)面狀態(tài)保持。
使用 AutomaticKeepAliveClientMixin 進(jìn)行頁(yè)面狀態(tài)保持
- 新建一個(gè)有狀態(tài)的 Widget 類
- 讓 State 子類混入
AutomaticKeepAliveClientMixin - 實(shí)現(xiàn)
wantKeepAlive方法,返回值為true - 在
build方法中調(diào)用父類的 build 方法,示例:super.build(context)
示例代碼展示
import 'package:flutter/material.dart';
class KeepAliveWrapper extends StatefulWidget {
final bool keepAlive;
final Widget child;
const KeepAliveWrapper({
super.key,
required this.child,
this.keepAlive = true,
});
@override
State<KeepAliveWrapper> createState() => _KeepAliveWrapperState();
}
class _KeepAliveWrapperState extends State<KeepAliveWrapper>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
@override
bool get wantKeepAlive => widget.keepAlive;
@override
void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
if (oldWidget.keepAlive != widget.keepAlive) {
updateKeepAlive();
}
super.didUpdateWidget(oldWidget);
}
}
以上代碼就是一個(gè)可以直接使用的頁(yè)面狀態(tài)保持的 Widget 類,使用方便快捷。使用如下:
TabBarView(
controller: _tabController,
children: [
// DynamicListPage 就是需要狀態(tài)保持的頁(yè)面
const KeepAliveWrapper(child: DynamicListPage()),
],
)