I am creating a Flutter application with a navigation drawer by using the Drawer class of the Material library. The Widget containing the Drawer is a StatefulWidget and the Scaffold's content is displayed according to the selected item on the navigation drawer. The content is either WidgetOne or WidgetTwo, both maintaining their own state as StatefulWidgets. See the code example below.
At the moment, when I change from one widget to another and back, the whole state of the earlier displayed widget is reloaded. This is not ideal, since both widgets have network calls from an API, and need to be redrawn accordingly.
What I've tried so far
- Implementing
AutomaticKeepAliveClientMixinon both sub widgets, as suggested here: https://stackoverflow.com/a/50074067/4009506. However, this does not seem to work. - Using an
IndexedStackas suggested here: https://stackoverflow.com/a/54999503/4009506. This loads all widgets directly, even if they are not yet displayed.
Code
class DrawerWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() => _DrawerState();
}
class _DrawerState extends State<DrawerWidget> {
Widget _activeWidget;
@override
void initState() {
_activeWidget = FirstWidget();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Drawer demo")),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
ListTile(
title: Text("First Widget"),
onTap: () {
setState(() {
_activeWidget = FirstWidget();
});
},
),
ListTile(
title: Text("Second Widget"),
onTap: () {
setState(() {
_activeWidget = SecondWidget();
});
},
),
],
),
),
body: _activeWidget);
}
}
class FirstWidget extends StatefulWidget {
// [..]
}
class SecondWidget extends StatefulWidget {
// [..]
}
Desired result
WidgetOne and WidgetTwo are only loaded on initial load (after selecting them in the Drawer). Switching to another widget and back should not reload the widget if it was already loaded earlier. The sub widgets should not load all directly, only when they are initially pressed.
Actual result
Both FirstWidget and SecondWidget are reloaded and redrawn each time they are selected in the Drawer.