The issue:
I have 2 tabs using Default Tabs Controller, like so:
Widget build(BuildContext context) {
return DefaultTabController(
length:
There are two issues here, the first:
When the TabController
switches tabs, it unloads the old widget tree to save memory. If you want to change this behavior, you need to mixin AutomaticKeepAliveClientMixin to your tab widget's state.
class _DealListState extends State<DealList> with AutomaticKeepAliveClientMixin<DealList> {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context); // need to call super method.
return /* ... */
}
}
The second issue is in your use of the FutureBuilder
-
If you provide a new Future
to a FutureBuilder
, it can't tell that the results would be the same as the last time, so it has to rebuild. (Remember that Flutter may call your build method up to once a frame).
return FutureBuilder(
future: this.loadDeals(), // Creates a new future on every build invocation.
/* ... */
);
Instead, you want to assign the future to a member on your State class in initState, and then pass this value to the FutureBuilder
. The ensures that the future is the same on subsequent rebuilds. If you want to force the State to reload the deals, you can always create a method which reassigns the _loadingDeals
member and calls setState
.
Future<...> _loadingDeals;
@override
void initState() {
_loadingDeals = loadDeals(); // only create the future once.
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context); // because we use the keep alive mixin.
return new FutureBuilder(future: _loadingDeals, /* ... */);
}