The default implementation of Material's Scaffold & BottomNavigationBar is to destroy and re-create each tab in each tab change.
In the case of CupertinoTabScaffold, CupertinoTabView and CupertinoPageScaffold the behavior is different: the state of each tab is maintained, so switching between tabs won't re-trigger the initState() method of the tab in each change.
My question is: how to modify this behaviour to act the same as Material? I want each tab to be destroyed and re-created, thus calling the initState() method in each tab change, same as with the Material Widgets.
Thanks.
I would say this is a hack, but one way to actually have elements rebuild is to just use new elements.
But obviously, you need the same widget class to be rendered, so how can it be new ?
Keys
.Flutter check the
type
of your widget as well as it'skey
(if provided) to validate whether anwidget
is same or not so as to rebuild.You can use keys this way. Consider this simple example.
I have a
Sample
class which I am using to build each screen in theCupertinoTabScaffold
. But instead of using it likeSample()
, I have passed an extrakey
parameter which is just a random number.Now, my
Sample
class looks like this,Now, even if you change something in your
SampleState
class and then visit anotherTab
and then comeback to the previousTab
, since you are using a newKey
, Flutter will think it is a newWidget
and will rebuild it.Problem solved.
However, I must ask, why though ?