Flutter保持頁面狀態AutomaticKeepAliveClientMixin


使用bottomNavigationBar切換底部tab,再切換回來就會丟失之前的狀態(重新渲染列表,丟失滾動條位置)。

解決方法

使用 AutomaticKeepAliveClientMixin

重寫 bool get wantKeepAlive => true;

build方法中調用super.build(context);

class _MovieListState extends State<MovieList> with AutomaticKeepAliveClientMixin {
  List movieList = new List();

  @override
  bool get wantKeepAlive => true;
    
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView.builder(
      itemCount: movieList.length,
      itemBuilder: (context, index) {
        return MovieItem(
          item: movieList[index],
        );
      },
    );
  }
}

達到保存列表狀態的效果

ss.gif

引用自官網的說明:

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

Then, whenever wantKeepAlive's value changes (or might change), the subclass should call updateKeepAlive.

The type argument T is the type of the StatefulWidget subclass of the State into which this class is being mixed.

參考鏈接:

AutomaticKeepAliveClientMixin mixin


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM