flutter-保持頁面狀態(切換頁面,頁面還在原來的位置,不重新加載接口)


AutomaticKeepAliveClientMixin

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

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

  • 使用的頁面必須是StatefulWidget,如果是StatelessWidget是沒辦法辦法使用的。
  • 其實只有兩個前置組件才能保持頁面狀態:PageViewIndexedStack
  • 重寫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) {}。。。。

 


免責聲明!

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



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