Flutter保持页面状态AutomaticKeepAliveClientMixin

Flutter切换tabar后不会保留tabbar状态 ,Flutter中为了节约内存不会保存widget的状态,widget都是临时变量。当我们使用TabBar,TabBarView是我们就会发现,切换tabarinitState又会被调用一次。

怎么为了让tabar一直保存在内存中,不被销毁?

添加AutomaticKeepAliveClientMixin,并设置为bool get wantKeepAlive => true;,这样就能一直保持当前不被initState了。

class TestListView extends StatefulWidget {
  @override
  _ChatPageState createState() => _ChatPageState();
}

//1.添加with AutomaticKeepAliveClientMixin
class _TestListViewState extends State
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
   //3.添加 super.build(context) 必须添加
    super.build(context);
    return Container();
  }

  //2.添加  bool get wantKeepAlive => true
  //不会被销毁,占内存中
  @override
  bool get wantKeepAlive => true;
}
1.添加with AutomaticKeepAliveClientMixin
class _TestListViewState extends State
    with AutomaticKeepAliveClientMixin{}
2.添加 bool get wantKeepAlive => true,是否保保持页面不变
  @override
  bool get wantKeepAlive => true;
3.添加 super.build(context) 必须添加
  @override
  Widget build(BuildContext context) {
   //3.添加 super.build(context) 必须添加
    super.build(context);
    return Container();
  }

你可能感兴趣的:(Flutter保持页面状态AutomaticKeepAliveClientMixin)