Flutter is unmounting my stateful widget with wantKeepAlive overridden to true - any suggestions?

1,202 views
Skip to first unread message

Keith Allen

unread,
May 15, 2019, 7:31:39 PM5/15/19
to Flutter Dev

I have a tabbed Flutter interface using the DefaultTabController with 3 pages, each a stateful widget. I seem to be able to switch between the first two tabs just fine, but when I tab to the 3rd page the state object for the first page gets disposed. Subsequent state updates (using setState()) then fail.


I've overridden the dispose() method of the state object for the first page so that it prints a message when disposed. It's getting disposed as soon as I hit the third tab. I can't find documentation on why Flutter disposes state objects. (Plenty on lifecycle but not the reasons for progressing through the stages.)

Nothing unusual about setting up the tabs, I don't think.

 @override
  Widget build(BuildContext context) {
    return new MaterialApp(

      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            title: Text(title),
            bottom: TabBar(
              tabs: [
                // Use these 3 icons on the tab bar.
                Tab(icon: Icon(Icons.tune)),
                Tab(icon: Icon(Icons.access_time)),
                Tab(icon: Icon(Icons.settings)),
              ],
            ),
          ),
          body: TabBarView(
            children: [
              // These are the 3 pages relating to to the tabs.
              ToolPage(),
              TimerPage(),
              SettingsPage(),
            ],

The pages themselves are pretty simple. No animation. Just switches and sliders, etc.


State on the first two pages gets updated when reading from a websocket this app opens to a remote server. 


The state object includes the AutomaticKeepAliveClientMixin and overrides wantKeepAlive to true. Also, I override dispose and print a message when the object is being disposed so I know when it happens and it prints that wantKeepAlive is true.


class _ToolPageState extends State<ToolPage> with AutomaticKeepAliveClientMixin<ToolPage> {...


@override
bool get wantKeepAlive => true;

@override
dispose
() {
 
print ("tool page state being disposed! wantKeepAlive is " + wantKeepAlive.toString());
 
super.dispose();
}




I would expect the State object associated with a StatefulWidget to stay around and with wantKeepAlive = true don't understand why it's being disposed when I click to the third tab. 


Any suggestions?

Chun-Heng Tai

unread,
May 15, 2019, 7:35:17 PM5/15/19
to Flutter Dev
This issue should be fixed in the latest master
I think it is till waiting for dev release. Let me know if it still happen with latest master

Keith Allen

unread,
May 17, 2019, 12:22:15 PM5/17/19
to Flutter Dev

Thanks!. I'll do that.

Reply all
Reply to author
Forward
0 new messages