Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

flutter - initState() method is not being called when widget reloads

I've a widget that has a Stateful widget as child. What I want is, some action to be triggered whenever this Stateful child widget reloads.

In the child widget I have this function,

//in child widget

 @override
  void initState() {
    super.initState();

    print("Inside Child Widget"); 
}

Problem is, it is printing this only the first time. After this, whenever there is a change in state of parent widget which leads to reloading of this child widget, this action does not get triggered.

I checked this answer initState function is't be called in StatefulWidget by default & I understand initstate() is called only once, however, when I reload the widget, it rebuilds, so shouldn't the function get triggered again?

question from:https://stackoverflow.com/questions/65640989/initstate-method-is-not-being-called-when-widget-reloads

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

init state is a method that can be used only to initialize the state the first time the widget is built. If you need to perform actions every time the widget is rebuilt use inside your build method (before returning)

WidgetsBinding.instance.addPostFrameCallback((_) {
  // executes after build
})

However, think carefully if what you are doing is correct. And remember that if you are setting a state inside this method you have to use set state.

InitState is not supposed to be re-executed since (usually) set state is the way you update the state afterwards. If you need to reload resources from external "sources" you can use futurebuilder or StreamBuilder


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...