解決Flutter使用 Scaffold + Tabbar + TabbarView保存頁面狀態問題

Flutter切換tab後默認不會保留tab狀態 ,Flutter中爲了節約內存不會保存widget的狀態,widget都是臨時變量。當我們使用TabBar,TabBarView是我們就會發現,切換tab,initState又會被調用一次。爲了讓tab一直保存在內存中不被銷燬。在需要保持頁面狀態的子頁State中,繼承AutomaticKeepAliveClientMixin並重寫wantKeepAlive爲true即可。

class FirstState extends State<FirstView>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Text('xixixi');
  }
  //不會被銷燬,佔內存中
  @override
  bool get wantKeepAlive => true;
}

notes:Subclasses must implement wantKeepAlive, and their build methods
must call super.build (the return value will always return null, and
should be ignored)

但是有時候還是不起作用,在需要保存頁面狀態的子tab頁面的build方法中調用父類build(context)。

  @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).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章