子init方法是在父对象是重建-flatter时调用的



据我所知和flutter的工作机制,有状态的小部件方法在小部件树中的第一次构建时只调用一次,而每次状态更改或父级重建时都调用构建方法。

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这里是一个类的状态之一,其中一个单独的主体小部件是基于_currentActivitIndex的值呈现的。

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

这是scaffold小部件的主体:-一个基于上面的_currentActivitIndex呈现的小部件。

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

每次在_curentActiveIndex更改的地方重建父对象(如上所述(时,都会调用PostLoadWidgetState initState((方法,这是所需的行为。我一直在初始化initState((中的网络调用,我不想在每次重建它的父级时都调用它。

您可以使用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

最新更新