408 lines
16 KiB
Dart
408 lines
16 KiB
Dart
import 'dart:async';
|
||
import 'dart:typed_data';
|
||
import 'dart:ui' as ui;
|
||
|
||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||
import 'package:flutter/foundation.dart'
|
||
show TargetPlatform, defaultTargetPlatform, kIsWeb;
|
||
import 'package:flutter/services.dart' show MethodChannel;
|
||
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 '../../../core/utils/coord_util.dart';
|
||
import '../../device/domain/device_models.dart';
|
||
import '../data/location_controller.dart';
|
||
|
||
/// 首页定位卡片的百度地图预览。
|
||
///
|
||
/// 根据传入的 [location](WGS84 坐标)将地图中心与标记定位到设备位置;
|
||
/// 地图加载完成后用快照替换原生视图。尺寸由父级约束决定。
|
||
class LocationMapView extends ConsumerStatefulWidget {
|
||
const LocationMapView({super.key, required this.location});
|
||
|
||
final DeviceLocation? location;
|
||
|
||
@override
|
||
ConsumerState<LocationMapView> createState() => _LocationMapViewState();
|
||
}
|
||
|
||
class _LocationMapViewState extends ConsumerState<LocationMapView>
|
||
with WidgetsBindingObserver, AutomaticKeepAliveClientMixin {
|
||
BMFMapController? _mapController;
|
||
bool _mapReady = false;
|
||
Uint8List? _snapshot;
|
||
|
||
@override
|
||
bool get wantKeepAlive => true;
|
||
|
||
/// 平台视图重建标记:app 从后台恢复后自增,用于强制重建
|
||
/// [BMFMapWidget](AndroidView / UiKitView),修复原生地图残留在上层的问题。
|
||
int _platformViewGeneration = 0;
|
||
|
||
/// 同一次预览复用选项,避免父级重建时重新创建原生视图。
|
||
late BMFMapOptions _mapOptions;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_mapOptions = _previewOptions();
|
||
// 监听 app 生命周期,app 从后台恢复时重建原生地图视图(见 didChangeAppLifecycleState)。
|
||
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 页面之上不消失。恢复前台时通过递增 generation 重建平台视图,
|
||
// 让原生地图重新挂载到正确层级(每次重建成本可控,仅发生于前后台切换)。
|
||
if (state == AppLifecycleState.resumed && _snapshot == null) {
|
||
_recreatePlatformView();
|
||
}
|
||
}
|
||
|
||
/// 通过替换 [BMFMapWidget] 的 key 强制重建平台视图,并复位内部状态。
|
||
void _recreatePlatformView() {
|
||
// 复位控制器/标记/就绪状态,等待新视图的 onMapCreated 重新初始化。
|
||
_mapController = null;
|
||
_mapReady = false;
|
||
setState(() {
|
||
_snapshot = null;
|
||
_mapOptions = _previewOptions();
|
||
_platformViewGeneration++;
|
||
});
|
||
}
|
||
|
||
@override
|
||
void didUpdateWidget(covariant LocationMapView oldWidget) {
|
||
super.didUpdateWidget(oldWidget);
|
||
if (_toWgsCoordinate(oldWidget.location) !=
|
||
_toWgsCoordinate(widget.location) ||
|
||
oldWidget.location?.sn != widget.location?.sn) {
|
||
_recreatePlatformView();
|
||
}
|
||
}
|
||
|
||
void _onMapCreated(BMFMapController controller) {
|
||
_mapController = controller;
|
||
debugPrint('[LocationMapView] onMapCreated, mapController 已就绪');
|
||
// 按官方「显示定位」文档:地图加载完成后再执行图层/覆盖物操作,
|
||
// 否则 addMarker / showUserLocation 等在地图未就绪时调用会不生效。
|
||
controller.setMapDidLoadCallback(callback: () async {
|
||
if (_mapController != controller || _mapReady) return;
|
||
_mapReady = true;
|
||
debugPrint('[LocationMapView] mapDidLoad, 执行图层与标记初始化');
|
||
// 1. 初始化定位图层 + 补偿蓝色定位点。
|
||
_enableUserLocationLayer();
|
||
// 2. 补偿添加设备位置 Marker(地图加载完成后 addMarker 才可靠)。
|
||
await _capturePreview(controller, widget.location);
|
||
});
|
||
}
|
||
|
||
/// 开启定位图层并设置定位点样式(地图加载完成后调用)。
|
||
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);
|
||
debugPrint('[LocationMapView] _enableUserLocationLayer: 当前定位状态=${current.runtimeType}');
|
||
if (current is LocationSuccess) _updateUserLocation(current.location);
|
||
}
|
||
|
||
/// 把手机本机定位结果更新到地图定位图层(蓝色定位点)。
|
||
void _updateUserLocation(DeviceCurrentLocation location) {
|
||
final controller = _mapController;
|
||
if (controller == null) {
|
||
debugPrint('[LocationMapView] _updateUserLocation 被丢弃:mapController 尚未就绪');
|
||
return;
|
||
}
|
||
debugPrint('[LocationMapView] _updateUserLocation lat=${location.latitude} '
|
||
'lon=${location.longitude}');
|
||
// 按百度地图「显示定位」文档构造完整位置对象。
|
||
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);
|
||
}
|
||
|
||
Future<void> _capturePreview(
|
||
BMFMapController controller,
|
||
DeviceLocation? location,
|
||
) async {
|
||
final coord = _toWgsCoordinate(location);
|
||
try {
|
||
final rendered = Completer<void>();
|
||
controller.setMapDidFinishedRenderCallback(callback: (success) {
|
||
if (success && !rendered.isCompleted) rendered.complete();
|
||
});
|
||
if (coord != null) {
|
||
final sn = location!.sn;
|
||
final icon = await deviceMarkerIconData(
|
||
sn != null && sn.isNotEmpty ? sn : '设备位置',
|
||
);
|
||
if (_mapController != controller) return;
|
||
if (icon != null) {
|
||
await controller.addMarker(
|
||
BMFMarker.iconData(
|
||
position: wgs84ToBd09(coord.lat, coord.lon),
|
||
iconData: icon,
|
||
identifier: 'device_location',
|
||
),
|
||
);
|
||
}
|
||
}
|
||
// 地图加载回调早于瓦片和覆盖物完成绘制。等待 SDK 渲染完成再截图。
|
||
await rendered.future.timeout(
|
||
const Duration(seconds: 2),
|
||
onTimeout: () {},
|
||
);
|
||
if (_mapController != controller) return;
|
||
final snapshot = await controller.takeSnapshot().timeout(
|
||
const Duration(seconds: 5),
|
||
);
|
||
if (_mapController != controller || snapshot == null || snapshot.isEmpty) {
|
||
return;
|
||
}
|
||
// 用普通 Flutter 图片参与列表滚动,释放持续合成的原生地图视图。
|
||
setState(() {
|
||
_mapController = null;
|
||
_snapshot = snapshot;
|
||
});
|
||
} catch (error) {
|
||
debugPrint('[LocationMapView] 生成地图预览失败: $error');
|
||
}
|
||
}
|
||
|
||
BMFMapOptions _previewOptions() => BMFMapOptions(
|
||
center: _computeCenter(widget.location),
|
||
zoomLevel: 16,
|
||
showMapScaleBar: false,
|
||
showZoomControl: false,
|
||
scrollEnabled: false,
|
||
zoomEnabled: false,
|
||
);
|
||
|
||
BMFCoordinate _computeCenter(DeviceLocation? location) {
|
||
final coord = _toWgsCoordinate(location);
|
||
if (coord != null) return wgs84ToBd09(coord.lat, coord.lon);
|
||
// 默认中心:北京
|
||
return BMFCoordinate(39.915, 116.404);
|
||
}
|
||
|
||
({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);
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
super.build(context);
|
||
final snapshot = _snapshot;
|
||
if (snapshot != null) {
|
||
return SizedBox.expand(child: Image.memory(snapshot, fit: BoxFit.cover));
|
||
}
|
||
// 监听本机定位结果:成功后把蓝色定位点更新到地图。
|
||
// ⚠️ Riverpod 要求 ref.listen 只能在 build 期间调用,故放在此处。
|
||
// 使用 ref.listen 而非 ref.watch:仅建立监听、**不使 build 依赖该状态**,
|
||
// 因此本机定位状态变化不会触发地图原生视图(AndroidView / UiKitView)重建,
|
||
// 这是首页下拉/滚动卡顿的关键优化。ref.listen 同样会触发 Provider 初始化以启动定位。
|
||
ref.listen<LocationState>(
|
||
locationControllerProvider,
|
||
(prev, next) {
|
||
debugPrint('[LocationMapView] listen 定位状态: ${next.runtimeType}');
|
||
if (next is LocationSuccess) {
|
||
_updateUserLocation(next.location);
|
||
} else if (next is LocationFailed) {
|
||
debugPrint('[Location] 首页卡片:定位失败 -> ${next.message}');
|
||
}
|
||
},
|
||
);
|
||
|
||
// 重要:BMFMapWidget 底层为 AndroidView / UiKitView,必须被包裹在
|
||
// 明确宽高的容器中(SizedBox.expand 强制铺满父级),否则地图会显示空白。
|
||
return SizedBox.expand(
|
||
child: BMFMapWidget(
|
||
// key 依赖平台视图重建代数:app 从后台恢复时强制重建原生地图,
|
||
// 修复地图 Surface 残留在其它页面之上的问题。
|
||
key: ValueKey('home_map_$_platformViewGeneration'),
|
||
onBMFMapCreated: _onMapCreated,
|
||
mapOptions: _mapOptions,
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// 设备位置 Marker 的 PNG 图标字节缓存(key 为 SN 标题)。
|
||
final Map<String, Uint8List> _deviceMarkerIconCache = {};
|
||
const _deviceMarkerChannel = MethodChannel('com.ttstd.familycare/app');
|
||
|
||
/// 生成设备位置 Marker 的 PNG 图标字节。
|
||
///
|
||
/// 图标为一个「带圆角边框的气泡标签」:上方是圆角矩形气泡(白底 + 深色描边边框,
|
||
/// 内含设备 SN 文字),下方是红色定位针,中间小三角衔接,整体形似带边框的气泡。
|
||
/// 用 `dart:ui` 动态绘制,宽度随 SN 文字长度自适应,超长 SN 自动降字号避免图标过宽变扁;
|
||
/// 高度固定偏高,保证竖长比例。避免依赖外部图片资源。
|
||
/// 绘制失败返回 null(调用方不做渲染)。
|
||
Future<Uint8List?> deviceMarkerIconData(String title) async {
|
||
final cached = _deviceMarkerIconCache[title];
|
||
if (cached != null) return cached;
|
||
try {
|
||
// Android 用软件 Canvas 生成位图,避开 Flutter 离屏光栅化时的缺字和填色异常。
|
||
if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) {
|
||
final bytes = await _deviceMarkerChannel.invokeMethod<Uint8List>(
|
||
'renderDeviceMarker',
|
||
title,
|
||
);
|
||
if (bytes != null) {
|
||
_deviceMarkerIconCache[title] = bytes;
|
||
return bytes;
|
||
}
|
||
}
|
||
|
||
// ---- 尺寸常量(整体放大:解决文字偏小 / 图标偏窄)----
|
||
const bubbleH = 80.0; // 气泡高度
|
||
const padX = 30.0; // 气泡左右内边距
|
||
const pinH = 72.0; // 下方定位针高度
|
||
const pinW = 60.0; // 定位针宽度
|
||
const tailH = 16.0; // 气泡与定位针之间的小三角高度
|
||
const totalH = bubbleH + tailH + pinH; // 图标总高(约 168)
|
||
const maxFontSize = 32.0; // 放大后字号上限
|
||
const minFontSize = 20.0; // 长 SN 时的字号下限
|
||
const maxBubbleW = 240.0; // 气泡最大宽度,防止图标过宽(但不裁文字、不换行)
|
||
|
||
// ---- 文字始终单行测量(宽约束取极大值,避免换行)----
|
||
double measureLine(String text, double fs) {
|
||
final pb = ui.ParagraphBuilder(ui.ParagraphStyle(fontSize: fs));
|
||
pb.addText(text);
|
||
final p = pb.build();
|
||
p.layout(const ui.ParagraphConstraints(width: 10000));
|
||
return p.longestLine;
|
||
}
|
||
|
||
// 优先大号;若单行仍超最大宽,则降字号直到放得下(下限 minFontSize)。
|
||
var fontSize = maxFontSize;
|
||
var textW = measureLine(title, fontSize);
|
||
while (textW + padX * 2 > maxBubbleW && fontSize > minFontSize) {
|
||
fontSize -= 2.0;
|
||
textW = measureLine(title, fontSize);
|
||
}
|
||
|
||
// 气泡宽度 = 单行文字宽 + 左右内边距,保证文字不换行、不被裁。
|
||
final finalBubbleW = textW + padX * 2;
|
||
final width = finalBubbleW.ceilToDouble().toInt();
|
||
final height = totalH.ceilToDouble().toInt();
|
||
|
||
final recorder = ui.PictureRecorder();
|
||
final canvas = ui.Canvas(recorder);
|
||
|
||
final cx = finalBubbleW / 2;
|
||
// ---- 气泡:白底 + 深色描边(圆角矩形)----
|
||
final bubbleRect = ui.RRect.fromRectAndRadius(
|
||
ui.Rect.fromLTWH(0, 0, finalBubbleW, bubbleH),
|
||
const ui.Radius.circular(10),
|
||
);
|
||
final bubbleFill = ui.Paint()..color = const ui.Color(0xFFFFFFFF);
|
||
canvas.drawRRect(bubbleRect, bubbleFill);
|
||
final bubbleStroke = ui.Paint()
|
||
..color = const ui.Color(0xFF1F2937)
|
||
..style = ui.PaintingStyle.stroke
|
||
..strokeWidth = 2;
|
||
canvas.drawRRect(bubbleRect, bubbleStroke);
|
||
|
||
// ---- 小三角:衔接气泡与定位针,同边框色 ----
|
||
final triangle = ui.Path()
|
||
..moveTo(cx - 9, bubbleH)
|
||
..lineTo(cx + 9, bubbleH)
|
||
..lineTo(cx, bubbleH + tailH)
|
||
..close();
|
||
canvas.drawPath(triangle, bubbleStroke);
|
||
|
||
// ---- SN 文字(深色,水平/垂直居中于气泡内)----
|
||
final paintPb = ui.ParagraphBuilder(ui.ParagraphStyle(
|
||
fontSize: fontSize,
|
||
textAlign: ui.TextAlign.center,
|
||
));
|
||
paintPb.pushStyle(ui.TextStyle(color: const ui.Color(0xFF1F2937)));
|
||
paintPb.addText(title);
|
||
final paintParagraph = paintPb.build();
|
||
paintParagraph.layout(ui.ParagraphConstraints(width: finalBubbleW));
|
||
final textLeft =
|
||
(finalBubbleW - paintParagraph.width) / 2; // 文字超宽时以气泡宽度为中心
|
||
canvas.drawParagraph(
|
||
paintParagraph,
|
||
ui.Offset(textLeft < 0 ? 0 : textLeft, (bubbleH - paintParagraph.height) / 2),
|
||
);
|
||
|
||
// ---- 红色定位针(更宽更高,比例竖长)----
|
||
final pinTop = bubbleH + tailH;
|
||
final halfPin = pinW / 2;
|
||
final pin = ui.Path()
|
||
..moveTo(cx, pinTop)
|
||
..cubicTo(cx - halfPin * 0.7, pinTop, cx - halfPin, pinTop + halfPin * 0.4,
|
||
cx - halfPin, pinTop + halfPin * 0.8)
|
||
..cubicTo(cx - halfPin, pinTop + pinH * 0.7, cx, pinTop + pinH, cx,
|
||
pinTop + pinH)
|
||
..cubicTo(cx, pinTop + pinH, cx + halfPin, pinTop + pinH * 0.7,
|
||
cx + halfPin, pinTop + halfPin * 0.8)
|
||
..cubicTo(cx + halfPin, pinTop + halfPin * 0.4, cx + halfPin * 0.7, pinTop,
|
||
cx, pinTop);
|
||
final pinFill = ui.Paint()..color = const ui.Color(0xFFE5484D);
|
||
canvas.drawPath(pin, pinFill);
|
||
final pinStroke = ui.Paint()
|
||
..color = const ui.Color(0xFFC0392B)
|
||
..style = ui.PaintingStyle.stroke
|
||
..strokeWidth = 2;
|
||
canvas.drawPath(pin, pinStroke);
|
||
// 针内白点。
|
||
final dot = ui.Paint()..color = const ui.Color(0xFFFFFFFF);
|
||
canvas.drawCircle(ui.Offset(cx, pinTop + pinH * 0.45), 8, dot);
|
||
|
||
final picture = recorder.endRecording();
|
||
final image = await picture.toImage(width, height);
|
||
final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
|
||
picture.dispose();
|
||
image.dispose();
|
||
if (byteData == null) return null;
|
||
final bytes = byteData.buffer.asUint8List();
|
||
_deviceMarkerIconCache[title] = bytes;
|
||
return bytes;
|
||
} catch (e) {
|
||
debugPrint('[DeviceMarker] 生成定位图标失败: $e');
|
||
return null;
|
||
}
|
||
}
|