From 8d3366fbf900e89b3434556a43ef154ca6bd2d5f Mon Sep 17 00:00:00 2001 From: Nedifinita Date: Sat, 27 Sep 2025 00:50:12 +0800 Subject: [PATCH] refactor --- lib/screens/history_screen.dart | 4 +- lib/screens/map_screen.dart | 88 ++------------------------ lib/services/background_service.dart | 41 ++++++------ lib/services/ble_service.dart | 4 +- lib/services/location_service.dart | 17 ++--- lib/services/map_state_service.dart | 32 ++++------ lib/services/notification_service.dart | 32 +++++++--- 7 files changed, 70 insertions(+), 148 deletions(-) diff --git a/lib/screens/history_screen.dart b/lib/screens/history_screen.dart index 2b7fdc4..128dfa2 100644 --- a/lib/screens/history_screen.dart +++ b/lib/screens/history_screen.dart @@ -712,9 +712,7 @@ class HistoryScreenState extends State { setState(() { _currentUserLocation = LatLng(position.latitude, position.longitude); }); - } catch (e) { - print('获取当前位置失败: $e'); - } + } catch (e) {} } void _startLocationUpdates() { diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 3c66342..80b3087 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -44,16 +44,12 @@ class _MapScreenState extends State { @override void initState() { super.initState(); - print('=== 地图页面初始化 ==='); _initializeMap(); _checkDatabaseSettings(); - // _loadSettings().then((_) { - print('设置加载完成,开始加载列车记录'); _loadTrainRecords().then((_) { - print('列车记录加载完成,开始位置更新'); _startLocationUpdates(); }); }); @@ -61,40 +57,28 @@ class _MapScreenState extends State { Future _checkDatabaseSettings() async { try { - print('=== 检查数据库设置 ==='); final dbInfo = await DatabaseService.instance.getDatabaseInfo(); - print('数据库信息: $dbInfo'); final settings = await DatabaseService.instance.getAllSettings(); - print('数据库设置详情: $settings'); if (settings != null) { final lat = settings['mapCenterLat']; final lon = settings['mapCenterLon']; - print('数据库中的位置坐标: lat=$lat, lon=$lon'); if (lat != null && lon != null) { if (lat == 39.9042 && lon == 116.4074) { - print('警告:数据库中保存的是北京默认坐标'); } else if (lat == 0.0 && lon == 0.0) { - print('警告:数据库中保存的是零坐标'); } else { - print('数据库中保存的是有效坐标'); final beijingLat = 39.9042; final beijingLon = 116.4074; final distance = _calculateDistance(lat, lon, beijingLat, beijingLon); - print('与北京市中心的距离: ${distance.toStringAsFixed(2)} 公里'); - if (distance < 50) { - print('注意:保存的位置在北京附近(距离 < 50公里)'); - } + if (distance < 50) {} } } } - } catch (e) { - print('检查数据库设置失败: $e'); - } + } catch (e) {} } double _calculateDistance( @@ -154,25 +138,20 @@ class _MapScreenState extends State { Future _getCurrentLocation() async { try { - print('=== 获取当前位置 ==='); Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, forceAndroidLocationManager: true, ); final newLocation = LatLng(position.latitude, position.longitude); - print('获取到位置: $newLocation'); setState(() { _userLocation = newLocation; }); if (!_isMapInitialized) { - print('获取位置后尝试初始化地图'); _initializeMapPosition(); } - } catch (e) { - print('获取位置失败: $e'); - } + } catch (e) {} } void _startLocationUpdates() { @@ -199,20 +178,13 @@ class _MapScreenState extends State { }); _mapController.move(newLocation, 15.0); - } catch (e) { - print('强制更新位置失败: $e'); - } + } catch (e) {} } Future _loadSettings() async { try { - print('=== 开始加载设置 ==='); final settings = await DatabaseService.instance.getAllSettings(); - print('设置数据: $settings'); if (settings != null) { - print( - '设置中的位置: lat=${settings['mapCenterLat']}, lon=${settings['mapCenterLon']}'); - print('设置中的缩放: ${settings['mapZoomLevel']}'); setState(() { _railwayLayerVisible = (settings['mapRailwayLayerVisible'] as int?) == 1; @@ -227,31 +199,17 @@ class _MapScreenState extends State { if (lat != null && lon != null && lat != 0.0 && lon != 0.0) { _currentLocation = LatLng(lat, lon); - print('使用保存的位置: $_currentLocation'); - } else { - print('保存的位置无效或为零,不使用'); } }); - print('设置加载完成,当前位置: $_currentLocation'); if (!_isMapInitialized) { - print('设置加载后尝试初始化地图'); _initializeMapPosition(); } - } else { - print('没有保存的设置数据'); } - } catch (e) { - print('加载设置失败: $e'); - } + } catch (e) {} } Future _saveSettings() async { try { - print('=== 保存设置到数据库 ==='); - print('当前旋转角度: $_currentRotation'); - print('当前缩放级别: $_currentZoom'); - print('当前位置: $_currentLocation'); - final center = _mapController.camera.center; final isDefaultLocation = @@ -269,20 +227,14 @@ class _MapScreenState extends State { settings['mapCenterLon'] = center.longitude; } - print('保存的设置数据: $settings'); await DatabaseService.instance.updateSettings(settings); - print('=== 设置保存成功 ==='); - } catch (e) { - print('保存设置失败: $e'); - } + } catch (e) {} } Future _loadTrainRecords() async { setState(() => _isLoading = true); try { - print('=== 开始加载列车记录 ==='); final records = await _getFilteredRecords(); - print('加载到 ${records.length} 条记录'); setState(() { _trainRecords.clear(); _trainRecords.addAll(records); @@ -290,33 +242,22 @@ class _MapScreenState extends State { if (_trainRecords.isNotEmpty) { final lastRecord = _trainRecords.first; - print( - '最新记录: ${lastRecord.fullTrainNumber}, 位置: ${lastRecord.position}'); final coords = lastRecord.getCoordinates(); final dmsCoords = _parseDmsCoordinate(lastRecord.positionInfo); if (dmsCoords != null) { _lastTrainLocation = dmsCoords; - print('使用DMS坐标: $dmsCoords'); } else if (coords['lat'] != 0.0 && coords['lng'] != 0.0) { _lastTrainLocation = LatLng(coords['lat']!, coords['lng']!); - print('使用解析坐标: $_lastTrainLocation'); - } else { - print('记录中没有有效坐标'); } - } else { - print('没有列车记录'); } - print('列车位置: $_lastTrainLocation'); if (!_isMapInitialized) { - print('列车记录加载后尝试初始化地图'); _initializeMapPosition(); } }); } catch (e) { setState(() => _isLoading = false); - print('加载列车记录失败: $e'); } } @@ -338,31 +279,18 @@ class _MapScreenState extends State { LatLng? targetLocation; - print('=== 初始化地图位置 ==='); - print('当前位置: $_currentLocation'); - print('列车位置: $_lastTrainLocation'); - print('用户位置: $_userLocation'); - print('地图已初始化: $_isMapInitialized'); - if (_currentLocation != null) { targetLocation = _currentLocation; - print('使用保存的坐标: $targetLocation'); } else if (_lastTrainLocation != null) { targetLocation = _lastTrainLocation; - print('使用列车位置: $targetLocation'); } else if (_userLocation != null) { targetLocation = _userLocation; - print('使用用户位置: $targetLocation'); } else { targetLocation = const LatLng(39.9042, 116.4074); - print('没有可用位置,使用北京默认位置: $targetLocation'); } - print('最终选择位置: $targetLocation'); - print('当前旋转角度: $_currentRotation'); _centerMap(targetLocation!, zoom: _currentZoom, rotation: _currentRotation); _isMapInitialized = true; - print('地图初始化完成,旋转角度: $_currentRotation'); } void _centerMap(LatLng location, {double? zoom, double? rotation}) { @@ -392,9 +320,7 @@ class _MapScreenState extends State { return LatLng(lat, lng); } } - } catch (e) { - print('解析DMS坐标失败: $e'); - } + } catch (e) {} return null; } diff --git a/lib/services/background_service.dart b/lib/services/background_service.dart index 92bbef8..3587606 100644 --- a/lib/services/background_service.dart +++ b/lib/services/background_service.dart @@ -20,9 +20,9 @@ class BackgroundService { if (_isInitialized) return; final service = FlutterBackgroundService(); - + final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); - + if (Platform.isAndroid) { const AndroidNotificationChannel channel = AndroidNotificationChannel( _notificationChannelId, @@ -34,10 +34,12 @@ class BackgroundService { playSound: false, ); - await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation< - AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); + await flutterLocalNotificationsPlugin + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>() + ?.createNotificationChannel(channel); } - + await service.configure( androidConfiguration: AndroidConfiguration( onStart: _onStart, @@ -81,8 +83,9 @@ class BackgroundService { if (service is AndroidServiceInstance) { await Future.delayed(const Duration(seconds: 1)); if (await service.isForegroundService()) { - final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); - + final flutterLocalNotificationsPlugin = + FlutterLocalNotificationsPlugin(); + try { const AndroidNotificationChannel channel = AndroidNotificationChannel( _notificationChannelId, @@ -94,8 +97,10 @@ class BackgroundService { playSound: false, ); - await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation< - AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); + await flutterLocalNotificationsPlugin + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>() + ?.createNotificationChannel(channel); await flutterLocalNotificationsPlugin.show( _notificationId, @@ -122,10 +127,7 @@ class BackgroundService { ), ), ); - print('前台服务通知显示成功'); - } catch (e) { - print('前台服务通知显示失败: $e'); - } + } catch (e) {} } } @@ -136,8 +138,9 @@ class BackgroundService { final bleService = BLEService(); final isConnected = bleService.isConnected; final deviceStatus = bleService.deviceStatus; - - final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); + + final flutterLocalNotificationsPlugin = + FlutterLocalNotificationsPlugin(); await flutterLocalNotificationsPlugin.show( _notificationId, 'LBJ Console', @@ -163,9 +166,7 @@ class BackgroundService { ), ), ); - } catch (e) { - print('前台服务通知更新失败: $e'); - } + } catch (e) {} } } }); @@ -179,7 +180,7 @@ class BackgroundService { static Future startService() async { await initialize(); final service = FlutterBackgroundService(); - + if (Platform.isAndroid) { final isRunning = await service.isRunning(); if (!isRunning) { @@ -208,4 +209,4 @@ class BackgroundService { service.invoke('setAsBackground'); } } -} \ No newline at end of file +} diff --git a/lib/services/ble_service.dart b/lib/services/ble_service.dart index 6fc4722..dd7887c 100644 --- a/lib/services/ble_service.dart +++ b/lib/services/ble_service.dart @@ -330,9 +330,7 @@ class BLEService { _dataController.add(trainRecord); DatabaseService.instance.insertRecord(trainRecord); } - } catch (e) { - print("$TAG: JSON Decode Error: $e, Data: $jsonData"); - } + } catch (e) {} } void _updateConnectionState(bool connected, String status) { diff --git a/lib/services/location_service.dart b/lib/services/location_service.dart index 9347b2d..991b897 100644 --- a/lib/services/location_service.dart +++ b/lib/services/location_service.dart @@ -12,7 +12,8 @@ class LocationService { LatLng? _currentLocation; Timer? _locationTimer; bool _isLocationPermissionGranted = false; - final StreamController _locationStreamController = StreamController.broadcast(); + final StreamController _locationStreamController = + StreamController.broadcast(); Stream get locationStream => _locationStreamController.stream; LatLng? get currentLocation => _currentLocation; @@ -30,7 +31,6 @@ class LocationService { try { bool serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { - print('定位服务未开启'); return; } @@ -40,14 +40,11 @@ class LocationService { } if (permission == LocationPermission.deniedForever) { - print('定位权限被拒绝,请在设置中开启'); return; } _isLocationPermissionGranted = true; - } catch (e) { - print('请求定位权限失败: $e'); - } + } catch (e) {} } Future _getCurrentLocation() async { @@ -56,14 +53,12 @@ class LocationService { try { Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, - forceAndroidLocationManager: true, // 强制使用Android LocationManager + forceAndroidLocationManager: true, ); _currentLocation = LatLng(position.latitude, position.longitude); _locationStreamController.add(_currentLocation); - } catch (e) { - print('获取当前位置失败: $e'); - } + } catch (e) {} } void _startLocationUpdates() { @@ -86,4 +81,4 @@ class LocationService { _locationTimer?.cancel(); _locationStreamController.close(); } -} \ No newline at end of file +} diff --git a/lib/services/map_state_service.dart b/lib/services/map_state_service.dart index 4acb2c0..654a578 100644 --- a/lib/services/map_state_service.dart +++ b/lib/services/map_state_service.dart @@ -9,7 +9,7 @@ class MapStateService { MapStateService._internal(); static const String _tableName = 'record_map_states'; - + final Map _memoryCache = {}; Future _ensureTableExists() async { @@ -34,10 +34,10 @@ class MapStateService { Future saveMapState(String key, MapState state) async { try { _memoryCache[key] = state; - + final db = await DatabaseService.instance.database; await _ensureTableExists(); - + await db.insert( _tableName, { @@ -47,9 +47,7 @@ class MapStateService { }, conflictAlgorithm: ConflictAlgorithm.replace, ); - } catch (e) { - print('保存地图状态失败: $e'); - } + } catch (e) {} } Future getMapState(String key) async { @@ -60,7 +58,7 @@ class MapStateService { try { final db = await DatabaseService.instance.database; await _ensureTableExists(); - + final result = await db.query( _tableName, where: 'key = ?', @@ -74,16 +72,14 @@ class MapStateService { _memoryCache[key] = state; return state; } - } catch (e) { - print('读取地图状态失败: $e'); - } - + } catch (e) {} + return null; } Future deleteMapState(String key) async { _memoryCache.remove(key); - + try { final db = await DatabaseService.instance.database; await db.delete( @@ -91,23 +87,19 @@ class MapStateService { where: 'key = ?', whereArgs: [key], ); - } catch (e) { - print('删除地图状态失败: $e'); - } + } catch (e) {} } Future clearAllMapStates() async { _memoryCache.clear(); - + try { final db = await DatabaseService.instance.database; await db.delete(_tableName); - } catch (e) { - print('清空地图状态失败: $e'); - } + } catch (e) {} } void clearMemoryCache() { _memoryCache.clear(); } -} \ No newline at end of file +} diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 6173793..f9adc17 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -90,20 +90,32 @@ class NotificationService { String _buildNotificationContent(TrainRecord record) { final buffer = StringBuffer(); - buffer.writeln('车次: ${record.fullTrainNumber}'); - buffer.writeln('线路: ${record.route}'); - buffer.writeln('方向: ${record.directionText}'); + buffer.write(record.fullTrainNumber); + if (_isValidValue(record.route)) { + buffer.write(' ${record.route}'); + } + if (_isValidValue(record.directionText)) { + buffer.write(' ${record.directionText}'); + } + if (_isValidValue(record.positionInfo)) { + buffer.write(' ${record.positionInfo}'); + } + buffer.writeln(); + if (_isValidValue(record.locoType) && _isValidValue(record.loco)) { + final shortLoco = record.loco.length > 5 + ? record.loco.substring(record.loco.length - 5) + : record.loco; + buffer.write('${record.locoType}-$shortLoco'); + } else if (_isValidValue(record.locoType)) { + buffer.write(record.locoType); + } else if (_isValidValue(record.loco)) { + buffer.write(record.loco); + } if (_isValidValue(record.speed)) { - buffer.writeln('速度: ${record.speed} km/h'); + buffer.write(' ${record.speed}km/h'); } - if (_isValidValue(record.positionInfo)) { - buffer.writeln('位置: ${record.positionInfo}'); - } - - buffer.writeln('时间: ${record.formattedTime}'); - return buffer.toString().trim(); }