I am displaying Google Maps using Flutter, and I want to change the appearance of the Google Map when the device's appearance mode is changed. But, the onMapCreated
property of Google Maps is not being executed. How can I change the appearance of the Google Map when the app returns from the background?
I have successfully achieved synchronizing the theme of the app itself with the device's appearance settings and updating it when returning from the background. However, I am currently unable to change the mapStyle of Google Maps.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MapSample(),
);
}
}
class MapSample extends StatefulWidget {
const MapSample({super.key});
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> with WidgetsBindingObserver {
final Completer<GoogleMapController> _controller = Completer();
late Brightness justBeforeMode;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (AppLifecycleState.paused == state) {
justBeforeMode = ui.window.platformBrightness;
}
if (AppLifecycleState.resumed == state) {
if (ui.window.platformBrightness != justBeforeMode) {
setState(() {});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ui.window.platformBrightness == Brightness.light
?
// lightMode
GoogleMap(
mapType: MapType.normal,
initialCameraPosition: const CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
),
onMapCreated: (GoogleMapController controller) async {
_controller.complete(controller);
},
)
:
// darkMode
GoogleMap(
mapType: MapType.normal,
initialCameraPosition: const CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
),
onMapCreated: (GoogleMapController controller) async {
final darkGoogleMapStyle = await rootBundle
.loadString('assets/jsons/dark_map_style.json');
await controller.setMapStyle(darkGoogleMapStyle);
_controller.complete(controller);
},
),
);
}
}
Someone asked a similar question here, but I couldn't find a solution: