Files
flutterApp/lib/features/home/presentation/widgets/common/commonFn.dart

96 lines
3.3 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
/// 定位质量解析 + 缓存管理 工具类
class LocationUtils {
// ==================== 1. 缓存键常量(全局复用) ====================
static const String kSavedPlotData = 'saved_plot_data';
static const String kSavedGcjPathPoints = 'saved_gcj_path_points';
static const String kSavedGcjOuterPoints = 'saved_gcj_outer_points';
static const String kSavedMarkedPoints = 'saved_marked_points';
static const String kSavedObstacleHoles = 'saved_obstacle_holes';
static const String kSavedIsWorkAreaCompleted = 'saved_is_work_area_completed';
// ==================== 2. 定位质量解析相关方法 ====================
/// 解析定位质量值为可读字符串
/// [locationValue] 定位质量编码(0/1/2/4/5)
/// 返回:对应的中文描述
static String parseLocationQuality(int locationValue) {
switch (locationValue) {
case 0:
return '无效';
case 1:
return 'GPS 单点定位';
case 2:
return 'DGPS 伪距差分或 SBAS';
case 4:
return 'RTK 固定解';
case 5:
return 'RTK 浮点解';
default:
return '未知($locationValue)';
}
}
static String parseControlMode(int value) {
switch (value) {
case 3:
return '远程控制';
default:
return '本地控制';
}
}
/// 校验定位质量是否有效
static bool isLocationValid(int locationValue) {
return locationValue != 0;
}
// ==================== 3. 缓存操作相关方法(可选扩展,按需添加) ====================
/// 保存坐标点数组到 SharedPreferences(自动序列化)
static Future<void> saveLatLngList(String key, List<dynamic> points) async {
final prefs = await SharedPreferences.getInstance();
// 将数组序列化为 JSON 字符串存储
await prefs.setString(key, json.encode(points));
}
/// 读取坐标点数组(自动反序列化)
static Future<List<dynamic>> getLatLngList(String key) async {
final prefs = await SharedPreferences.getInstance();
final jsonStr = prefs.getString(key);
if (jsonStr == null || jsonStr.isEmpty) return [];
try {
return json.decode(jsonStr) as List<dynamic>;
} catch (e) {
print('读取缓存数组失败: $e, key=$key');
return [];
}
}
/// 清除指定缓存键
static Future<void> clearCache(String key) async {
final prefs = await SharedPreferences.getInstance();
if (prefs.containsKey(key)) {
await prefs.remove(key);
}
}
/// 清除所有定位/地块相关缓存(仅清除本类定义的键)
static Future<void> clearAllPlotCache() async {
final prefs = await SharedPreferences.getInstance();
// 批量清除本类定义的缓存键
final cacheKeys = [kSavedPlotData, kSavedGcjPathPoints, kSavedGcjOuterPoints, kSavedMarkedPoints, kSavedObstacleHoles, kSavedIsWorkAreaCompleted];
for (final key in cacheKeys) {
if (prefs.containsKey(key)) {
await prefs.remove(key);
}
}
}
// 在 LocationUtils 类中添加
static Future<bool> getBool(String key, {bool defaultValue = false}) async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(key) ?? defaultValue;
}
}