import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart'; import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart'; import '../../../core/utils/coord_util.dart'; import '../../../l10n/app_localizations.dart'; import '../../device/data/device_providers.dart'; import '../../device/domain/device_models.dart'; import '../../device/presentation/device_switcher.dart'; import '../data/location_controller.dart'; import 'location_map_view.dart'; /// 设备实时位置地图页。 /// /// 基于百度地图展示设备上报的实时位置。定位数据来自 /// `GET /api/v1/client/sn/device-info`(经 [deviceLocationProvider] 解析), /// 后端返回 GPS(WGS84) 坐标,展示前转换为百度 BD09LL 坐标。 class MapPage extends ConsumerStatefulWidget { const MapPage({required this.sn, super.key}); final String sn; @override ConsumerState createState() => _MapPageState(); } class _MapPageState extends ConsumerState with WidgetsBindingObserver { BMFMapController? _mapController; bool _markerAdded = false; // 是否正在「定位到我」:点击定位按钮后置 true,拿到本机定位后归 false。 bool _isLocatingSelf = false; // 平台视图重建代数:app 从后台恢复时自增,强制重建原生地图(见 _recreatePlatformView)。 int _platformViewGeneration = 0; @override void initState() { super.initState(); // 监听 app 生命周期,app 从后台恢复时重建原生地图视图。 WidgetsBinding.instance.addObserver(this); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); // 地图控制器由底层平台视图生命周期管理,销毁时主动清空本地引用, // 避免 teardown 阶段对已释放的原生视图发起调用(降低百度 SDK 原生崩溃风险)。 _mapController = null; super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { // 切换到桌面(paused)再返回时,百度地图原生 Surface 可能残留在其它 // Flutter 页面之上不消失。恢复前台时重建平台视图让其重新挂载到正确层级。 if (state == AppLifecycleState.resumed) { _recreatePlatformView(); } } /// 通过替换 [BMFMapWidget] 的 key 强制重建平台视图,并复位内部状态。 void _recreatePlatformView() { _mapController = null; _markerAdded = false; setState(() => _platformViewGeneration++); } @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context); final locationAsync = ref.watch(deviceLocationProvider(widget.sn)); // watch 本机定位 Provider:首次进入自动启动手机定位,页面销毁时自动停止。 ref.watch(locationControllerProvider); // 监听定位数据(ref.listen 只能在 build 方法内调用):无论地图创建时序如何 // (地图后建/数据后到),只要数据就绪就主动把地图中心与标记同步到设备位置, // 避免依赖 build 帧时序导致地图停留在默认中心。 ref.listen>( deviceLocationProvider(widget.sn), (prev, next) { if (next.hasValue) _syncLocation(next.valueOrNull); }, ); // 监听本机定位结果:定位成功后把蓝色定位点更新到地图(BMFUserLocation)。 // 若正处于「定位到我」流程,则把地图中心同步到本机位置并复位标记。 ref.listen( locationControllerProvider, (prev, next) { if (next is LocationSuccess) { _updateUserLocation(next.location); if (_isLocatingSelf) { _moveToUserLocation(next.location); setState(() => _isLocatingSelf = false); } } else if (next is LocationFailed) { debugPrint('[Location] 全屏地图:定位失败 -> ${next.message}'); if (_isLocatingSelf) setState(() => _isLocatingSelf = false); } }, ); // 设备坐标(WGS84)转百度坐标,作为地图初始中心;无数据时回退到北京。 final BMFCoordinate center = _computeCenter(locationAsync.valueOrNull); return AppPageScaffold( navigationBar: CupertinoNavigationBar( middle: DeviceContextTitle(l10n.mapTitle), previousPageTitle: l10n.back, ), child: SafeArea( child: Stack( children: [ BMFMapWidget( // key 依赖平台视图重建代数:app 从后台恢复时强制重建原生地图, // 修复地图 Surface 残留在其它页面之上的问题。 key: ValueKey('full_map_$_platformViewGeneration'), onBMFMapCreated: _onMapCreated, mapOptions: BMFMapOptions( center: center, zoomLevel: 16, showMapScaleBar: true, ), ), _buildOverlay(locationAsync, l10n), _buildLocateButton(l10n), ], ), ), ); } /// 地图创建完成回调。 void _onMapCreated(BMFMapController controller) { _mapController = controller; // 按官方「显示定位」文档:地图加载完成后再执行图层/覆盖物操作, // 否则 showUserLocation / addMarker 等在地图未就绪时调用会不生效。 controller.setMapDidLoadCallback(callback: () { _enableUserLocationLayer(); // 补偿添加设备位置 Marker(地图加载完成后 addMarker 才可靠)。 _syncLocation(ref.read(deviceLocationProvider(widget.sn)).valueOrNull); }); } /// 开启定位图层并设置定位点样式(地图加载完成后调用)。 void _enableUserLocationLayer() { final controller = _mapController; if (controller == null) return; // 1. 开启定位图层。 controller.showUserLocation(true); // 2. 设置定位点样式(使用 SDK 默认图标;不设置无效图片路径,避免图标加载失败)。 final param = BMFUserLocationDisplayParam.userlocationOptions() ..isAccuracyCircleShow = true ..accuracyCircleFillColor = const Color(0x3300B0FF) ..accuracyCircleStrokeColor = const Color(0x6600B0FF) ..locationViewHierarchy = BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_TOP; controller.updateLocationViewWithParam(param); // 3. 若本机定位已就绪,同步蓝色定位点。 final current = ref.read(locationControllerProvider); if (current is LocationSuccess) _updateUserLocation(current.location); } /// 把手机本机定位结果更新到地图定位图层(蓝色定位点)。 void _updateUserLocation(DeviceCurrentLocation location) { final controller = _mapController; if (controller == null) return; // 按百度地图「显示定位」文档构造完整位置对象。 final userLocation = BMFUserLocation( location: BMFLocation( coordinate: BMFCoordinate(location.latitude, location.longitude), altitude: location.altitude ?? 0, horizontalAccuracy: location.radius ?? 0, verticalAccuracy: -1.0, speed: location.speed ?? -1.0, course: location.course ?? -1.0, ), ); controller.updateLocationData(userLocation); } /// 把地图中心移动到本机定位位置(不带动画也行,这里用动画平滑过渡)。 void _moveToUserLocation(DeviceCurrentLocation location) { final controller = _mapController; if (controller == null) return; controller.setCenterCoordinate( BMFCoordinate(location.latitude, location.longitude), true, ); } /// 右下角「定位到我」浮动按钮:点击后重新启动本机定位, /// 定位成功会在 listen 回调中把地图中心移到本机位置。 Widget _buildLocateButton(AppLocalizations l10n) { final isLocating = _isLocatingSelf; return Positioned( right: 6, bottom: 100, child: CupertinoButton( padding: EdgeInsets.zero, onPressed: isLocating ? null : _onLocateMe, child: Container( width: 40, height: 40, decoration: BoxDecoration( color: CupertinoColors.systemBackground.withValues(alpha: 0.92), shape: BoxShape.circle, boxShadow: const [ BoxShadow( color: Color(0x33000000), blurRadius: 6, offset: Offset(0, 2), ), ], ), child: isLocating ? const CupertinoActivityIndicator(radius: 11) : const Icon( CupertinoIcons.location_fill, size: 22, color: CupertinoColors.activeBlue, ), ), ), ); } /// 点击「定位到我」:标记进入定位中,重新启动手机本机定位。 void _onLocateMe() { // 若已经拿到过本机位置,先立即把中心移过去(定位回调通常很快,提升即时反馈)。 final current = ref.read(locationControllerProvider); if (current is LocationSuccess) { _moveToUserLocation(current.location); } setState(() => _isLocatingSelf = true); ref.read(locationControllerProvider.notifier).restart(); } /// 根据最新定位刷新地图标记与中心。 void _syncLocation(DeviceLocation? location) { final controller = _mapController; if (controller == null) return; final coord = _toWgsCoordinate(location); if (coord == null) return; final bd = wgs84ToBd09(coord.lat, coord.lon); controller.setCenterCoordinate(bd, true); if (!_markerAdded) { // Marker 标题展示设备 SN(缺失时兜底为"设备位置")。 final sn = location!.sn; final title = (sn != null && sn.isNotEmpty) ? sn : '设备位置'; // 使用 iconData 指定图标:基础 BMFMarker(position:, title:) 构造不带 icon, // 在 Android 端不渲染(SDK 3.1.0 起已废弃),故传入红色定位点 PNG 字节。 _addDeviceMarker(controller, bd, title); } } /// 添加设备位置红点 Marker。 /// /// 图标由 [deviceMarkerIconData] 动态绘制为「带圆角边框的气泡 + 定位针」, /// 内含设备 SN 文字与边框,不依赖 `titleOptions`(其无边框能力)。 Future _addDeviceMarker( BMFMapController controller, BMFCoordinate position, String title, ) async { final icon = await deviceMarkerIconData(title); if (icon == null || _markerAdded) return; // 并发保护,避免重复添加。 final marker = BMFMarker.iconData( position: position, iconData: icon, identifier: 'device_location', ); await controller.addMarker(marker); _markerAdded = true; } /// 计算初始地图中心。 BMFCoordinate _computeCenter(DeviceLocation? location) { final coord = _toWgsCoordinate(location); if (coord != null) return wgs84ToBd09(coord.lat, coord.lon); // 默认中心:北京 return BMFCoordinate(39.915, 116.404); } /// 从 [DeviceLocation] 提取合法的 WGS84 坐标,缺失或非数字时返回 null。 ({double lat, double lon})? _toWgsCoordinate(DeviceLocation? location) { if (location == null) return null; final latStr = location.latitude; final lonStr = location.longitude; if (latStr == null || latStr.isEmpty || lonStr == null || lonStr.isEmpty) { return null; } final lat = double.tryParse(latStr); final lon = double.tryParse(lonStr); if (lat == null || lon == null) return null; return (lat: lat, lon: lon); } Widget _buildOverlay( AsyncValue locationAsync, AppLocalizations l10n) { return locationAsync.when( loading: () => const Center(child: CupertinoActivityIndicator()), error: (e, _) => Center( child: Padding( padding: const EdgeInsets.all(24), child: Text( l10n.snapshotLocationFailed, style: const TextStyle(color: CupertinoColors.systemGrey), textAlign: TextAlign.center, ), ), ), data: (location) { if (_toWgsCoordinate(location) == null) { return Center( child: Padding( padding: const EdgeInsets.all(24), child: Text( l10n.noSnapshotLocation, style: const TextStyle(color: CupertinoColors.systemGrey), textAlign: TextAlign.center, ), ), ); } // 定位数据已就绪且有效:地图中心与标记的同步由 ref.listen + _onMapCreated 负责, // 这里无需重复调度。 return const SizedBox.shrink(); }, ); } }