child init method is called when parent is rebuild - flutter

℡╲_俬逩灬. 提交于 2019-12-24 00:09:14

问题


As far as i understand and working mechanism of flutter a stateful widget method is only called once when its first build in the widget tree and build method method is called every time when its state is changed or the parent is rebuild.

 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 here is one of the state of a class where a seperate body widget is rendered based on the value of _currentActiveIndex.

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

This is the body of scaffold widget:- a widget rendered based on the _currentActiveIndex above.

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

Every time parents is rebuild (above) where the _curentActiveIndex is changed the PostLoadWidgetState initState() method is called which is the desired behaviour. I have been initializing networking call in initState() which i don't want to call on every rebuild of its parents.


回答1:


You can use the mixin AutomaticKeepAliveClientMixin and override the wantKeepAlive getter and return true to avoid recreating the State every time.

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


            ...

            @override
            bool get wantKeepAlive => true;

        }

More info here: https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc



来源:https://stackoverflow.com/questions/53134538/child-init-method-is-called-when-parent-is-rebuild-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!