Home > Software design >  Why "this" changes also without a new class statefull widget screen instance?
Why "this" changes also without a new class statefull widget screen instance?

Time:08-01

I have a screen as statefull widget. When I instance it I have the same "this" in initState and build methods, as expected. But if, from that screen, I open a new screen and than I come back to the first screen, first the statefull widget screen doesn't appear to be reinstanced, the method initState is not called again but the method build is called (as expected, the screen has to be drawed again) and it has a new "this" than the first time the screen has been displayed. I could also accept the screen class has a new this but how is it possibile without a new instance of the screen widget? It seems the class change its "this" without a new instance of the class. Is it possibile? Why? Am I wrong?

CodePudding user response:

By documents of flutter's stateful initstate

Called when this object is inserted into the tree.

The framework will call this method exactly once for each State object it creates.

Which means when you added the stateful widget for the first time this method is called and this (instance) is created..

Now the build method is called on various situations

The framework calls this method in a number of different situations. For example:

  • After calling initState.
  • After calling didUpdateWidget.
  • After receiving a call to setState.
  • After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes).
  • After calling deactivate and then reinserting the State object into the tree at another location.

So each timethe build is called a new instance is created if you have added the code to create an instance in build method.

When you move to the next page the first screen is still in widget tree. Then you pop screen 2 so you see screen1 ahain but this time its not added to the widget tree so only the build is called.. if you do navigator.push from screen 2 and navigate to screen 1 you will see initstate being called again because a new instance of screen1 is added to the widget tree..

  • Related