重建父级时调用子级init方法-flutter

时间:2018-11-03 19:01:17

标签: dart flutter hybrid-mobile-app

据我所知,Flutter的工作机制只有在状态树第一次在窗口树中构建时才被调用一次,而每次状态改变或父对象被重建时都会被调用build方法。

>
 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()中初始化网络调用,我不想在每次父级重建时都调用它。

1 个答案:

答案 0 :(得分:1)

您可以使用mixin AutomaticKeepAliveClientMixin并覆盖wantKeepAlive getter并返回true以避免每次都重新创建State。

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


            ...

            @override
            bool get wantKeepAlive => true;

        }

此处有更多信息:https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

相关问题