skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search