I have a Stateful widget WidgetOne
that I’m wrapping into a Visibility
widget to control its visibility.
The goal is to have multiple created at the same time but only one visible (for a desktop-like tabs behavior).
Listview to show "tab bar":
ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: [
for (int i=0; i < 3; i++)
InkWell(
onTap: () => setSate(() =>_index = i),
child: Text('Element $i'),
)
]
),
The Column that creates all WidgetOne
widgets and make only 1 visible at a time (depending on _index value):
Column(
children: [
for (int i=0; i < 3; i++)
Visibility(
visibile: i == _index,
child: WidgetOne() //My stateful widget which I want it to avoid dispose
)
]
)
With this implementation, each time _index
value is updated and the state is rebuilt, the dispose()
methods of all non visible WidgetOne widgets are called and they are removed from the widget tree.
Is there any way to make sure that they are not disposed but only hidden instead?
2
Answers
You can set the
maintainState
property totrue
.In the documentation, the
maintainState
property is described as:You’re probably looking for the
Offstage
widget:And/or see my other How can I pre-load a route in flutter, or keep a widget loaded even when it is off screen? for using
IndexedStack