解决Flutter使用 Scaffold + Tabbar + TabbarView保存页面状态问题

Flutter切换tab后默认不会保留tab状态 ,Flutter中为了节约内存不会保存widget的状态,widget都是临时变量。当我们使用TabBar,TabBarView是我们就会发现,切换tab,initState又会被调用一次。为了让tab一直保存在内存中不被销毁。在需要保持页面状态的子页State中,继承AutomaticKeepAliveClientMixin并重写wantKeepAlive为true即可。

class FirstState extends State
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Text('xixixi');
  }
  //不会被销毁,占内存中
  @override
  bool get wantKeepAlive => true;
}

notes:Subclasses must implement wantKeepAlive, and their build methods
must call super.build (the return value will always return null, and
should be ignored)

但是有时候还是不起作用,在需要保存页面状态的子tab页面的build方法中调用父类build(context)。

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

原因:

A mixin with convenience methods for clients of [AutomaticKeepAlive]. Used with [State] subclasses.
/
Subclasses must implement [wantKeepAlive], and their [build] methods must call super.build (the return value will always return null, and should be ignored).

你可能感兴趣的:(flutter)