flutter AutomaticKeepAliveClientMixin不起作用?

weixin_34320159發表於2019-01-24

參考 https://www.colabug.com/3162835.html
https://stackoverflow.com/questions/53011686/flutter-automatickeepaliveclientmixin-is-not-working-with-bottomnavigationbar62835.html

Flutter切換tab後保留tab狀態 概述 Flutter中為了節約記憶體不會儲存widget的狀態,widget都是臨時變數。當我們使用TabBar,TabBarView是我們就會發現,切換tab,initState又會被呼叫一次。
怎麼為了讓tab一直儲存在記憶體中,不被銷燬?
新增AutomaticKeepAliveClientMixin,並設定為true,這樣就能一直保持當前不被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]);
          },
        ));
  }
  //不會被銷燬,佔記憶體中
  @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).

相關文章