AutomaticKeepAliveClientMixin
AutomaticKeepAliveClientMixin
這個Mixin
就是Flutter為了保持頁面設置的。哪個頁面需要保持頁面狀態,就在這個頁面進行混入。
不過使用使用這個Mixin
是有幾個先決條件的:
- 使用的頁面必須是
StatefulWidget
,如果是StatelessWidget
是沒辦法辦法使用的。 - 其實只有兩個前置組件才能保持頁面狀態:
PageView
和IndexedStack
。 - 重寫
wantKeepAlive
方法,如果不重寫也是實現不了的。
//主頁面(index_page) import 'package:flutter/material.dart'; //是由谷歌推出 import 'package:flutter/cupertino.dart';// IOS風格 import 'cart_page.dart'; import 'home_page.dart'; import 'member_page.dart'; import 'category_page.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class IndexPage extends StatefulWidget { @override _IndexPageState createState() => _IndexPageState(); } class _IndexPageState extends State<IndexPage> { int currentIndex=0; var currentPage; @override void initState() { super.initState(); currentPage=tabBodies[currentIndex]; } final List<Widget> tabBodies=[ HomePage(), CartPage(), CateGory(), MemberPage() ]; 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('會員中心'), ), ]; @override Widget build(BuildContext context) { print('設備像素密度:${ScreenUtil.pixelRatio}'); // print("${ScreenUtil.screenHeight}"); // print('設備寬度:${ScreenUtil.screenWidth}'); ScreenUtil.init(width: 750,height: 1334,allowFontScaling: true); return Scaffold( backgroundColor: Color.fromRGBO(244, 245, 245, 1.0), bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.fixed, currentIndex: currentIndex, items: bottomTabs, onTap: (index){ setState(() { currentIndex=index; currentPage=tabBodies[currentIndex]; }); }, ), body: IndexedStack( index: currentIndex,//當前頁面序號 children: tabBodies,//必須返回的是組件 ), ); } }
//組件 class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin { // String homePageContent='正在獲取數據'; @override bool get wantKeepAlive => true; //必須重寫 @override void initState() { super.initState(); } @override Widget build(BuildContext context) {}。。。。