Reputation: 1180
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?
Upvotes: 0
Views: 618
Reputation: 20088
You're probably looking for the Offstage
widget:
A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit testing, and without taking any room in the parent.
Offstage(
offstage: _offstage,
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
Upvotes: 1
Reputation: 8499
You can set the maintainState
property to true
.
Visibility(
maintainState: true,
// ...
)
In the documentation, the maintainState
property is described as:
Whether to maintain the State objects of the child subtree when it is not visible.
Upvotes: 2