參考 https://www.colabug.com/3162835.html
https://stackoverflow.com/questions/53011686/flutter-automatickeepaliveclientmixin-is-not-working-with-bottomnavigationbar62835.html
Flutter切換tab后保留tab狀態(tài) 概述 Flutter中為了節(jié)約內(nèi)存不會(huì)保存widget的狀態(tài),widget都是臨時(shí)變量。當(dāng)我們使用TabBar,TabBarView是我們就會(huì)發(fā)現(xiàn),切換tab秕岛,initState又會(huì)被調(diào)用一次膘婶。
怎么為了讓tab一直保存在內(nèi)存中丸氛,不被銷(xiāo)毀罚舱?
添加AutomaticKeepAliveClientMixin
井辜,并設(shè)置為true,這樣就能一直保持當(dāng)前不被initState了。
class TicketListViewState extends State<TicketListView>
with AutomaticKeepAliveClientMixin {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return new SmartRefresher(
enablePullDown: true,
enablePullUp: true,
onRefresh: _onRefresh,
controller: refreshController,
child: ListView.builder(
itemCount: _result.length,
itemBuilder: (context, index) {
return getItem(_result[index]);
},
));
}
//不會(huì)被銷(xiāo)毀,占內(nèi)存中
@override
bool get wantKeepAlive => true;
}
如果不起作用
@override
Widget build(BuildContext context) {
super.build(context);//必須添加
.....
));
官方解釋
/// A mixin with convenience methods for clients of [AutomaticKeepAlive]. Used
/// with [State] subclasses.
///
/// Subclasses must implement [wantKeepAlive], and their [build] methods must
/// call `super.build` (the return value will always return null, and should be
/// ignored).