首页 > 解决方案 > 重建父级时调用子级初始化方法 - 颤动

问题描述

据我了解和颤动的工作机制,有状态的小部件方法仅在其第一次在小部件树中构建时调用一次,而每次更改其状态或重建父级时调用构建方法方法。

 bottomNavigationBar: BottomNavigationBar(items: [
      BottomNavigationBarItem(icon: new Icon(Icons.home,), title: new Text("HOME", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.message,), title: new Text("MESSAGES", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.notifications,), title: new Text("NOTIFICATIONS", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.assignment,), title: new Text("MENTOR", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.account_circle,), title: new Text("PROFILE", style: new TextStyle(fontSize: 11.0),),),
    ],
      onTap: (int index){
        setState(() {
          _currentActiveIndex = index;
        });
      },
      currentIndex: _currentActiveIndex,
      type: BottomNavigationBarType.shifting,
    ),
    body: _getCurrentPage(_currentActiveIndex),

这里的 _currentActiveIndex 是基于 _currentActiveIndex 的值呈现单独的主体小部件的类的状态之一。

 body: TabBarView(children: <Widget>[
      new PostLoadWidget.express(),
      new PostLoadWidget.confess(),
    ]),

这是脚手架小部件的主体:- 基于上面的 _currentActiveIndex 呈现的小部件。

class PostLoadWidgetState extends State<PostLoadWidget> {
   @override
   void initState(){
       print("initState is called here);
       super.initState();
    }
}

每次重建父母时(上图),其中 _curentActiveIndex 发生更改,都会调用 PostLoadWidgetState initState() 方法,这是所需的行为。我一直在 initState() 中初始化网络调用,我不想在每次重建其父级时都调用它。

标签: dartflutterhybrid-mobile-app

解决方案


您可以使用 mixinAutomaticKeepAliveClientMixin并覆盖wantKeepAlivegetter 并返回 true 以避免每次都重新创建 State。

        class PostLoadWidgetState extends State<PostLoadWidget> with AutomaticKeepAliveClientMixin<PostLoadWidget> {


            ...

            @override
            bool get wantKeepAlive => true;

        }

更多信息在这里:https ://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc


推荐阅读