我在 flutter 中使用了谷歌地图,想要在更改应用程序模式(深色或浅色)时在样式(深色和浅色)之间切换,但状态未更新! ,我使用 getx 包作为状态管理,并尝试使用另一个状态管理和本机有状态但结果相同..样式地图未更新,我不知道谷歌中的问题或我更新状态的方式。
代码:
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(22.r),
topRight: Radius.circular(22.r),
),
child: Container(
width: Get.width,
height: 446.h,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(22.r),
topRight: Radius.circular(22.r))),
child: GetBuilder<ReservationTrackController>(
builder: (trackController) {
return GoogleMap(
zoomControlsEnabled: false,
mapToolbarEnabled: false,
markers: trackController.markers,
onTap: (LatLng? position) {
trackController
.changeMarkerPosition(position);
},
initialCameraPosition: trackController
.initialCameraPosition,
onMapCreated:
(GoogleMapController controller) {
trackController.mapController =
controller;
controller
.setMapStyle(trackController.isLight? MapStyle.lightGreen:MapStyle.greenDarkSpy);
},
);
}
),
),
)
我在 getxController 中使用 update() 来更新更改。
我尝试在地图样式(深色和浅色)之间切换。 我希望更改应用程序模式时更新地图样式。 实际上什么也没发生。
您必须将
controller
变量存储在某处,最好是在使用 StatefulWidget
的状态下。例如:
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
// Define a nullable variable here, we'll assign it later
GoogleMapController? googleMapController;
@override
Widget build(BuildContext context) {
// ...
}
}
现在在
onMapCreated
回调中,将控制器分配给 googleMapController
变量:
onMapCreated: (GoogleMapController controller) {
// ...
googleMapController = controller;
}
之后,如果您想更改地图样式,只需调用
setMapStyle
中的 googleMapController
方法即可。例如:
MaterialButton(
child: Text('A button to set map style'),
onPressed: () {
googleMapController?.setMapStyle( /* ... */ );
}
)
您可以将此逻辑适应您首选的状态管理解决方案。例如,在您的情况下,亮/暗模式基于
isLight
的值,因此您可以进行任何更改 isLight
的操作来调用此 googleMapController?.setMapStyle(...)
。或者,您也可以使用监听器来监听 isLight
的值变化,并在变化时调用 setMapStyle
。