I have 2 widgets. A parent StatefulWidget
which changes states multiple times during first full load, and a child StatelessWidget
which is expensive to build.
The reason the the child widget is expensive to build is because it is using google_maps_flutter
library which is using web view to display google maps on screen.
If possible, I want build()
function in this child widget to be executed only once.
However, whenever the parent widget is getting built multiple times due to state changes, it seems like the child widget is also getting built multiple times. Due to this, I see a bit of stuttering/lagging when the screen loads for the first time.
What is the best way to prevent child widget from getting rebuilt multiple times?
Below is a sample code.
Parent Widget
class ParentWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
Completer<GoogleMapController> _controller = Completer();
LocationPosition _myPosition;
@override
void initState() {
super.initState();
initialize();
}
void initialize(){
....// other initialization logic which may call `setState()` multiple times
}
Set<Marker> getMarkers(){
....
}
@override
Widget build(BuildContext context) {
return Scaffold(body: GoogleMapWidget(_controller, _myPosition, getMarkers()));
}
}
Child widget
class GoogleMapWidget extends StatelessWidget {
static const double ZOOM = 15;
final Completer<GoogleMapController> _controller;
final Set<Marker> markers;
final LocationPosition _myPosition;
GoogleMapWidget(this._controller, this._myPosition, this.markers);
@override
Widget build(BuildContext context) {
print("Rebuilt"); // <-- This gets printed multiple times, which is not something I want.
return GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng(_myPosition.lat, _myPosition.lng),
zoom: ZOOM,
),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
markers: markers);
}
}