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( 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) {}。。。。
原文地址:https://www.cnblogs.com/lxz-blogs/p/13272090.html