Flutter 頁(yè)面狀態(tài)保持

使用 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)保持

  1. 新建一個(gè)有狀態(tài)的 Widget 類
  2. 讓 State 子類混入 AutomaticKeepAliveClientMixin
  3. 實(shí)現(xiàn) wantKeepAlive 方法,返回值為 true
  4. 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()),
    ],
)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容