美文网首页
Flutter保持页面状态AutomaticKeepAliveC

Flutter保持页面状态AutomaticKeepAliveC

作者: 致青春_bf42 | 来源:发表于2020-11-10 09:37 被阅读0次

    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<TestListView>
        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<TestListView>
        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保持页面状态AutomaticKeepAliveC

          本文链接:https://www.haomeiwen.com/subject/luhrbktx.html