Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Google Maps state in Flutter

So I basically have an application with three tabs. On one of them, I have a Google Map with corresponding markers and a listener with a location based Firestore query. When the tab is selected, nearby elements will be queried and presented on the map.

However, when I change the tab and go back to the map again, the map, the listener and all the markers will be setup again (since initState() and dispose() were called).

What is the best way to save all the states from the map and continue on the previous state of the map, when the page is selected?

I have read something regarding Redux and BloC, is this the pattern I will need here? If yes, how can this be applied to the GoogleMap?

like image 644
Thomas Avatar asked Jan 28 '23 05:01

Thomas


2 Answers

I had the same problem, Flutter is basically reloading your googlemaps page everytime you change page. I solved this using IndexedStack. So I have all my pages in the stack all the time and they wont reload. I'm not sure if this is the best way but it works.

 child: new IndexedStack(
    children: _pages,
    index: widget.currentItem,
  ),

IndexedStack only shows the index item of the Stack, but all the items are in the stack even though they are not shown, so they wont be reloaded when you change the tab. Change the currentItem depending on the index of TabBar index with setState...

like image 152
user10456190 Avatar answered Feb 09 '23 03:02

user10456190


You can actually force Flutter to keep the widget tree alive using AutomaticKeepAliveClientMixin like so:

class LocationMapScreen extends StatefulWidget {
  @override
  _LocationMapScreenState createState() => _LocationMapScreenState();
}

class _LocationMapScreenState extends State<LocationMapScreen>
     with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  // ....
}
like image 30
Aron Avatar answered Feb 09 '23 03:02

Aron