Flutter移動電商實戰-切換后頁面狀態的保持AutomaticKeepAliveClientMixin


底欄切換每次都重新請求是一件非常惡心的事,flutter 中提供了AutomaticKeepAliveClientMixin 幫我們完成頁面狀態保存效果。

1、AutomaticKeepAliveClientMixin

AutomaticKeepAliveClientMixin 這個 Mixin 是 Flutter 為了保持頁面設置的。哪個頁面需要保持頁面狀態,就在這個頁面進行混入。

不過使用使用這個 Mixin 是有幾個先決條件的:

  • 使用的頁面必須是 StatefulWidget,如果是 StatelessWidget 是沒辦法辦法使用的。
  • 其實只有兩個前置組件才能保持頁面狀態:PageView 和 IndexedStack。
  • 重寫 wantKeepAlive 方法,如果不重寫也是實現不了的。

2、修改index_page.dart

明白基本知識之后,就可以修改 index_page.dart,思路就是增加一個 IndexedStack 包裹在 tabBodies 外邊。

整體代碼如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'home_page.dart';
import 'category_page.dart';
import 'cart_page.dart';
import 'member_page.dart';


class IndexPage extends StatefulWidget {
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>{

  PageController _pageController;

  final List<BottomNavigationBarItem> bottomTabs = [
    BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.home),
      title:Text('首頁')
    ),
    BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.search),
      title:Text('分類')
    ),
    BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.shopping_cart),
      title:Text('購物車')
    ),
     BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.profile_circled),
      title:Text('會員中心')
    ),
  ];

  final List<Widget> tabBodies = [
    HomePage(),
    CategoryPage(),
    CartPage(),
    MemberPage()
  ];

  int currentIndex= 0;
  var currentPage ;

  @override
  void initState() {
   currentPage=tabBodies[currentIndex];
   _pageController=new PageController()
      ..addListener(() {
        if (currentPage != _pageController.page.round()) {
          setState(() {
            currentPage = _pageController.page.round();
          });
        }
  });
  super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(2442452451.0),
      bottomNavigationBar: BottomNavigationBar(
        type:BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        items:bottomTabs,
        onTap: (index){
          setState(() {
           currentIndex=index;
            currentPage =tabBodies[currentIndex]; 
          });

        },
      ),
      body: IndexedStack(
        index: currentIndex,
        children: tabBodies
      )
    );
  }
}

3、加入Mixin保持頁面狀態

在 home_page.dart 里加入 AutomaticKeepAliveClientMixin 混入,加入后需要重寫 wantKeepAlive 方法。

主要代碼如下:

class _HomePageState extends State<HomePagewith AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive =>true;
}

為了檢驗結果,我們在 HomePageState 里增加一個 initState,在里邊 print 一些內容,如果內容輸出了,證明我們的頁面重新加載了,如果沒輸出,證明我們的頁面保持了狀態。

@override
void initState() {
    super.initState();
    print('我打印了哈哈哈哈哈');
}


免責聲明!

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



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