From 0ee4b2e1c764dcce4824212f581cc755f29163c9 Mon Sep 17 00:00:00 2001 From: TongTongStudio Date: Tue, 10 Nov 2026 21:20:18 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=B9=E8=BF=9B=E8=BF=9C=E7=A8=8B?= =?UTF-8?q?=E5=BD=95=E5=B1=8F=E4=BF=9D=E5=AD=98=E4=B8=8E=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E9=A6=96=E9=A1=B5=E4=BD=93=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + android/app/src/main/AndroidManifest.xml | 6 +- .../com/ttstd/familycare/MainActivity.java | 10 +- ios/Runner/AppDelegate.swift | 18 ++ ios/Runner/Info.plist | 2 + lib/features/apps/presentation/apps_page.dart | 103 ++++++++--- .../connection/data/video_recorder.dart | 168 ++++++++++-------- .../presentation/connection_controller.dart | 80 +++++---- .../presentation/remote_control_page.dart | 46 ++++- lib/features/device/data/device_api.dart | 27 ++- .../device/data/device_providers.dart | 21 ++- .../device/data/device_repository_impl.dart | 10 ++ .../device/domain/device_repository.dart | 4 + lib/features/home/presentation/home_page.dart | 30 +--- lib/features/home/presentation/home_tab.dart | 33 ++-- 15 files changed, 362 insertions(+), 197 deletions(-) diff --git a/.gitignore b/.gitignore index 2088348..ab91c06 100644 --- a/.gitignore +++ b/.gitignore @@ -47,3 +47,4 @@ app.*.map.json .widget_preview/ android/.kotlin/ .codebuddy/ +/.workbuddy/ diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 56bfcec..1630107 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -21,7 +21,7 @@ - + @@ -42,10 +42,6 @@ android:label="ttstd_family_care" android:name=".AppApplication" android:icon="@mipmap/ic_launcher"> - - - - 用于扫描设备二维码完成绑定 NSPhotoLibraryUsageDescription 用于查看本机相册照片并按文件夹浏览,以及从相册选取二维码图片完成设备绑定 + NSPhotoLibraryAddUsageDescription + 用于将远程屏幕录制保存到系统相册 io.flutter.embedded_views_preview diff --git a/lib/features/apps/presentation/apps_page.dart b/lib/features/apps/presentation/apps_page.dart index 90e9e84..0be1319 100644 --- a/lib/features/apps/presentation/apps_page.dart +++ b/lib/features/apps/presentation/apps_page.dart @@ -1,4 +1,7 @@ +import 'dart:async'; + import 'package:ttstd_family_care/core/network/cached_network_image.dart'; +import 'package:ttstd_family_care/core/network/error_message.dart'; import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; @@ -12,15 +15,49 @@ import 'package:ttstd_family_care/app/theme/dark_mode.dart'; import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart'; /// 应用列表页(对接 client「已安装应用」接口)。 -class AppsPage extends ConsumerWidget { +class AppsPage extends ConsumerStatefulWidget { const AppsPage({super.key}); @override - Widget build(BuildContext context, WidgetRef ref) { + ConsumerState createState() => _AppsPageState(); +} + +class _AppsPageState extends ConsumerState { + Timer? _reloadTimer; + + @override + void dispose() { + _reloadTimer?.cancel(); + super.dispose(); + } + + Future _refreshApps(String sn, AppLocalizations l10n) async { + String? error; + try { + error = await ref.read(deviceRepositoryProvider).sendDeviceOp(sn, 'refresh'); + } catch (exception) { + error = userMessageOf(exception); + } + if (!mounted || ref.read(selectedDeviceSnProvider) != sn) return; + if (error != null) { + _showAppOpResult(context, l10n, error); + return; + } + + _reloadTimer?.cancel(); + _reloadTimer = Timer(const Duration(seconds: 5), () { + if (ref.read(selectedDeviceSnProvider) == sn) { + ref.invalidate(deviceApksProvider(sn)); + } + }); + } + + @override + Widget build(BuildContext context) { final l10n = AppLocalizations.of(context); final sn = ref.watch(selectedDeviceSnProvider); final appsAsync = sn == null - ? const AsyncValue>.data(const []) + ? const AsyncValue>.data([]) : ref.watch(deviceApksProvider(sn)); return PopScope( @@ -44,34 +81,54 @@ class AppsPage extends ConsumerWidget { ), ), child: SafeArea( - child: appsAsync.when( - loading: () => const Center(child: CupertinoActivityIndicator()), - error: (e, _) => Center( - child: Text('${l10n.appsLoadFailed}:$e', - style: TextStyle(color: DarkMode.color(context, AppColors.sub))), + child: CustomScrollView( + physics: const AlwaysScrollableScrollPhysics( + parent: BouncingScrollPhysics(), ), - data: (apps) { - if (apps.isEmpty) { - return Center( - child: Text(l10n.appsEmpty, - style: TextStyle(color: DarkMode.color(context, AppColors.sub))), - ); - } - return ListView.builder( - padding: const EdgeInsets.all(16), - itemCount: apps.length, - itemBuilder: (context, index) { - final app = apps[index]; - return _appCell(context, ref, l10n, sn, app); + slivers: [ + if (sn != null) + CupertinoSliverRefreshControl( + onRefresh: () => _refreshApps(sn, l10n), + ), + appsAsync.when( + loading: () => const SliverFillRemaining( + hasScrollBody: false, + child: Center(child: CupertinoActivityIndicator()), + ), + error: (_, _) => _statusSliver(context, l10n.appsLoadFailed), + data: (apps) { + if (apps.isEmpty) { + return _statusSliver(context, l10n.appsEmpty); + } + return SliverPadding( + padding: const EdgeInsets.all(16), + sliver: SliverList.builder( + itemCount: apps.length, + itemBuilder: (context, index) => + _appCell(context, ref, l10n, sn, apps[index]), + ), + ); }, - ); - }, + ), + ], ), ), ), ); } + Widget _statusSliver(BuildContext context, String message) { + return SliverFillRemaining( + hasScrollBody: false, + child: Center( + child: Text( + message, + style: TextStyle(color: DarkMode.color(context, AppColors.sub)), + ), + ), + ); + } + Widget _appCell( BuildContext context, WidgetRef ref, diff --git a/lib/features/connection/data/video_recorder.dart b/lib/features/connection/data/video_recorder.dart index 46df64a..70ef08b 100644 --- a/lib/features/connection/data/video_recorder.dart +++ b/lib/features/connection/data/video_recorder.dart @@ -1,99 +1,111 @@ import 'dart:io'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:photo_manager/photo_manager.dart'; -/// 远程视频录制器:基于 flutter_webrtc 的 [MediaRecorder], -/// 把远端视频轨道(MediaStreamTrack)直接封装为 MP4 保存到本地。 -/// -/// 跨平台(Android / iOS)由 flutter_webrtc 内部完成 H.264 编码与封装, -/// 无需自行触碰原生 VideoSink。 -/// -/// 录制文件保存位置: -/// - Android:/Android/data/<包名>/files/WebRTCRecordings/(app 专属外部存储,无需存储权限) -/// - iOS:<App>/Documents/WebRTCRecordings/ +/// 先完成 MP4 封装,再导出到系统媒体库。 class VideoRecorder { + static const _channel = MethodChannel('com.ttstd.familycare/app'); + static const _screenRecordingsDirectory = 'Movies/Screen recordings'; + MediaRecorder? _recorder; - bool _recording = false; - String? _currentPath; + File? _recordingFile; + Future? _starting; + Future? _stopping; - /// 是否正在录制。 - bool get isRecording => _recording; - - /// 是否为空(从未真正开始)。 - String? get currentPath => _currentPath; - - /// 开始录制指定媒体流中的视频轨道。 - /// - /// 返回 true 表示成功开始;空流 / 无视频轨道会抛异常。 - Future start(MediaStream stream) async { - if (_recording) return false; - final videoTracks = stream.getVideoTracks(); - if (videoTracks.isEmpty) { - throw Exception('当前没有可用的远端视频轨道,无法录制'); + Future requestSavePermission() async { + if (Platform.isAndroid) { + final info = await DeviceInfoPlugin().androidInfo; + if (info.version.sdkInt >= 29) return true; + return (await Permission.storage.request()).isGranted; } - final path = await _buildOutputPath(); - // ignore: avoid_print - print('[VideoRecorder] 录制开始,保存地址:$path'); - _recorder = MediaRecorder(albumName: 'WebRTCRecordings'); - await _recorder!.start(path, videoTrack: videoTracks.first); - _currentPath = path; - _recording = true; - return true; + if (Platform.isIOS) { + final status = await PhotoManager.requestPermissionExtend( + requestOption: const PermissionRequestOption( + iosAccessLevel: IosAccessLevel.addOnly, + ), + ); + return status.hasAccess; + } + return false; + } + + Future start(MediaStream stream) { + final operation = _start(stream); + _starting = operation; + return operation.whenComplete(() => _starting = null); + } + + Future _start(MediaStream stream) async { + final tracks = stream.getVideoTracks(); + if (tracks.isEmpty) throw StateError('No remote video track'); + + final base = await getApplicationDocumentsDirectory(); + final directory = Directory('${base.path}/WebRTCRecordings'); + await directory.create(recursive: true); + final file = File( + '${directory.path}/screen-${DateTime.now().microsecondsSinceEpoch}.mp4', + ); + final recorder = MediaRecorder(); + await recorder.start(file.path, videoTrack: tracks.first); + _recorder = recorder; + _recordingFile = file; } - /// 停止录制,返回最终保存的文件路径;未开始录制返回 null。 Future stop() async { - if (!_recording || _recorder == null) return null; - try { - await _recorder!.stop(); - } catch (e) { - // 停止失败时仍清理状态,避免界面卡在"录制中" - // ignore: avoid_print - print('[VideoRecorder] stop error: $e'); - } finally { - _recorder = null; - _recording = false; - } - final p = _currentPath; - _currentPath = null; - // ignore: avoid_print - print('[VideoRecorder] 录制结束,已保存至:$p'); - return p; - } + await _starting; + final pending = _stopping; + if (pending != null) return pending; + + final recorder = _recorder; + final file = _recordingFile; + if (recorder == null || file == null) return null; - /// 释放资源(断开连接 / 页面销毁时调用)。 - Future dispose() async { - if (_recording && _recorder != null) { - try { - await _recorder!.stop(); - } catch (_) { - // 忽略 - } - } _recorder = null; - _recording = false; - _currentPath = null; + _recordingFile = null; + final operation = _finish(recorder, file); + _stopping = operation.whenComplete(() => _stopping = null); + return _stopping!; } - static String _pad(int n) => n.toString().padLeft(2, '0'); - - static Future _getRecordingDir() async { - final base = Platform.isAndroid - ? (await getExternalStorageDirectory())! - : await getApplicationDocumentsDirectory(); - final dir = Directory('${base.path}/WebRTCRecordings'); - if (!await dir.exists()) { - await dir.create(recursive: true); + Future _finish(MediaRecorder recorder, File file) async { + await recorder.stop(); + if (!await file.exists() || await file.length() == 0) { + throw StateError('Recording file is empty'); } - return dir; + final name = file.uri.pathSegments.last; + final String location; + if (Platform.isAndroid) { + final asset = await PhotoManager.editor.saveVideo( + file, + title: name, + relativePath: _screenRecordingsDirectory, + ); + final directory = asset.relativePath?.replaceFirst(RegExp(r'/+$'), ''); + location = directory == null || directory.isEmpty + ? 'Movies(系统相册 → 视频)' + : '$directory/${asset.title ?? name}'; + } else { + await _channel.invokeMethod('saveRecordingToPhotos', file.path); + location = '系统相册 / 视频 / $name'; + } + try { + await file.delete(); + } on FileSystemException { + // 已导出,应用内副本可留待清理。 + } + return location; } - static Future _buildOutputPath() async { - final dir = await _getRecordingDir(); - final now = DateTime.now(); - final name = 'rec_${now.year}${_pad(now.month)}${_pad(now.day)}_' - '${_pad(now.hour)}${_pad(now.minute)}${_pad(now.second)}.mp4'; - return '${dir.path}/$name'; + Future dispose() async { + try { + await stop(); + } catch (_) { + // 保留导出失败的录制文件,断开连接仍可完成。 + } } } diff --git a/lib/features/connection/presentation/connection_controller.dart b/lib/features/connection/presentation/connection_controller.dart index 8adbe1a..25c700b 100644 --- a/lib/features/connection/presentation/connection_controller.dart +++ b/lib/features/connection/presentation/connection_controller.dart @@ -280,44 +280,53 @@ class ConnectionController extends Notifier { ); } + bool _recordingBusy = false; + /// 切换远程视频录制:开始 / 停止。 Future toggleRecord() async { - if (state.recording) { - await _stopRecording(); - return; - } - await _startRecording(); - } - - Future _startRecording() async { - if (state.recording) return; - final renderer = _orchestrator?.remoteRenderer; - final stream = renderer?.srcObject; - if (stream == null) { - state = state.copyWith(recordStatus: '尚未接收到视频画面,无法录制'); - return; - } + if (_recordingBusy || _disposed) return; + _recordingBusy = true; + final orchestrator = _orchestrator; + final stopping = state.recording; try { - final ok = await _videoRecorder.start(stream); - if (ok) { - state = state.copyWith(recording: true, recordStatus: '录制中...'); + if (stopping) { + final location = await _videoRecorder.stop(); + if (_disposed || _orchestrator != orchestrator) return; + state = state.copyWith( + recording: false, + recordStatus: location == null ? '录制已停止' : '已保存:$location', + ); + return; } - } catch (e) { - state = state.copyWith(recordStatus: ''); - debugPrint('[record] 开始录制失败: $e'); - } - } - Future _stopRecording() async { - final path = await _videoRecorder.stop(); - state = state.copyWith( - recording: false, - recordStatus: path != null ? '已保存:$path' : '录制已停止', - ); + final stream = orchestrator?.remoteRenderer.srcObject; + if (stream == null) { + state = state.copyWith(recordStatus: '尚未接收到视频画面,无法录制'); + return; + } + final allowed = await _videoRecorder.requestSavePermission(); + if (_disposed || _orchestrator != orchestrator) return; + if (!allowed) { + state = state.copyWith(recordStatus: '请允许保存视频后再开始录制'); + return; + } + await _videoRecorder.start(stream); + if (_disposed || _orchestrator != orchestrator) return; + state = state.copyWith(recording: true, recordStatus: '录制中...'); + } catch (error) { + debugPrint('[record] 操作失败: $error'); + if (_disposed || _orchestrator != orchestrator) return; + state = state.copyWith( + recording: false, + recordStatus: stopping ? '保存到相册失败' : '无法开始录制', + ); + } finally { + _recordingBusy = false; + } } /// 关闭并清理。 - Future disconnect({String? errorMessage}) async { + Future disconnect({String? errorMessage}) async { final signaling = ref.read(signalingClientProvider); final orchestrator = _orchestrator; _orchestrator = null; @@ -329,13 +338,22 @@ class ConnectionController extends Notifier { orchestrator.onConnectionState = null; orchestrator.onReport = null; } - await _videoRecorder.dispose(); + String? recordStatus; + try { + final location = await _videoRecorder.stop(); + if (location != null) recordStatus = '已保存:$location'; + } catch (error) { + debugPrint('[record] 退出时保存失败: $error'); + recordStatus = '保存到相册失败'; + } await orchestrator?.dispose(); if (!_disposed) { state = ConnectionSessionState( state: errorMessage == null ? ConnectionState.ended : ConnectionState.error, errorMessage: errorMessage, + recordStatus: recordStatus ?? '', ); } + return recordStatus; } } diff --git a/lib/features/connection/presentation/remote_control_page.dart b/lib/features/connection/presentation/remote_control_page.dart index 0004201..505cccb 100644 --- a/lib/features/connection/presentation/remote_control_page.dart +++ b/lib/features/connection/presentation/remote_control_page.dart @@ -4,9 +4,11 @@ import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:ttstd_family_care/app/theme/dark_mode.dart'; import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart'; import '../../../core/platform/platform_capabilities.dart'; +import '../../../core/widgets/feature_ui.dart'; import '../../device/presentation/device_switcher.dart'; import '../data/connection_providers.dart'; import '../data/protobuf_codec.dart'; @@ -84,10 +86,24 @@ class _RemoteControlPageState extends ConsumerState { // 无论从哪个入口离开页面,都在 pop 后断开远程连接。 return PopScope( canPop: true, - onPopInvokedWithResult: (didPop, _) { - if (didPop) { - ref.read(connectionControllerProvider.notifier).disconnect(); - } + onPopInvokedWithResult: (didPop, _) async { + if (!didPop) return; + final navigator = Navigator.of(context, rootNavigator: true); + final message = await ref.read(connectionControllerProvider.notifier).disconnect(); + if (message == null || !navigator.mounted) return; + await showCupertinoDialog( + context: navigator.context, + builder: (dialogContext) => CupertinoAlertDialog( + title: const Text('屏幕录制'), + content: Text(message), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.of(dialogContext).pop(), + child: const Text('确定'), + ), + ], + ), + ); }, child: AppPageScaffold( navigationBar: CupertinoNavigationBar( @@ -298,8 +314,13 @@ class _RemoteControlPageState extends ConsumerState { return Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), decoration: BoxDecoration( - color: CupertinoColors.systemGroupedBackground, - border: Border(top: BorderSide(color: CupertinoColors.separator, width: 0.5)), + color: DarkMode.color(context, CupertinoColors.systemGroupedBackground), + border: Border( + top: BorderSide( + color: DarkMode.color(context, CupertinoColors.separator), + width: 0.5, + ), + ), ), child: Column( mainAxisSize: MainAxisSize.min, @@ -524,10 +545,19 @@ class _CtrlButton extends StatelessWidget { Icon( icon, size: 20, - color: enabled ? CupertinoColors.activeBlue : CupertinoColors.systemGrey3, + color: DarkMode.color( + context, + enabled ? CupertinoColors.activeBlue : CupertinoColors.systemGrey3, + ), ), const SizedBox(height: 4), - Text(label, style: const TextStyle(fontSize: 12)), + Text( + label, + style: TextStyle( + fontSize: 12, + color: DarkMode.color(context, enabled ? AppColors.ink : AppColors.sub), + ), + ), ], ), ); diff --git a/lib/features/device/data/device_api.dart b/lib/features/device/data/device_api.dart index ed16a3f..78bc391 100644 --- a/lib/features/device/data/device_api.dart +++ b/lib/features/device/data/device_api.dart @@ -87,6 +87,19 @@ class DeviceApi { } } + Future> getCachedMyDevices() async { + final data = await DioClient.readCachedGet('v1/client/sn/my-devices'); + return _parseList(data, DeviceBrief.fromJson); + } + + Future getCachedLocation(String sn) async { + final data = await DioClient.readCachedGet( + 'v1/client/sn/location', + queryParameters: {'sn': sn}, + ); + return data is Map ? DeviceLocation.fromJson(data) : null; + } + /// 获取已绑定设备最新定位信息(无上报数据时返回 null)。 Future getLocation(String sn) async { try { @@ -453,6 +466,18 @@ class DeviceApi { allowStale: true, queryParameters: query, ); + return _parseScreenshots(payload); + } + + Future> getCachedRecentScreenshots(String sn) async { + final payload = await DioClient.readCachedGet( + 'v1/client/sn/upload-screenshot', + queryParameters: {'sn': sn}, + ); + return _parseScreenshots(payload); + } + + List _parseScreenshots(dynamic payload) { // 防御性提取:兼容后台直接返回 List,或返回 { data: [...] } 的包裹结构。 final List listData; if (payload is List) { @@ -460,10 +485,8 @@ class DeviceApi { } else if (payload is Map && payload['data'] is List) { listData = payload['data'] as List; } else { - debugPrint('[DeviceApi] getRecentScreenshots 返回非预期结构: sn=$sn payload=$payload'); return const []; } - debugPrint('[DeviceApi] getRecentScreenshots sn=$sn count=${listData.length}'); final origin = Uri.parse(AppConstants.kBaseUrl).origin; return listData.whereType>().map((e) { final vo = ScreenshotVO.fromJson(e); diff --git a/lib/features/device/data/device_providers.dart b/lib/features/device/data/device_providers.dart index ad1b05a..02105ee 100644 --- a/lib/features/device/data/device_providers.dart +++ b/lib/features/device/data/device_providers.dart @@ -18,6 +18,20 @@ final myDevicesProvider = FutureProvider>((ref) async { return repo.getMyDevices(); }); +final _cachedMyDevicesProvider = FutureProvider>((ref) { + return ref.watch(deviceRepositoryProvider).getCachedMyDevices(); +}); + +final cachedDeviceLocationProvider = + FutureProvider.autoDispose.family((ref, sn) { + return ref.watch(deviceRepositoryProvider).getCachedLocation(sn); +}); + +final cachedRecentScreenshotsProvider = + FutureProvider.autoDispose.family, String>((ref, sn) { + return ref.watch(deviceRepositoryProvider).getCachedRecentScreenshots(sn); +}); + /// 用户手动选择的设备 SN。 /// /// 为空或对应设备已解绑时,[currentDeviceProvider] 自动回退到绑定列表首个设备, @@ -40,7 +54,12 @@ class SelectedDeviceSn extends Notifier { /// 绑定多个设备时以用户选择为准;刷新列表期间保留上一次数据, /// 解绑当前设备后自动落到新列表首个设备。 final currentDeviceProvider = Provider((ref) { - final list = ref.watch(myDevicesProvider).value ?? const []; + final devices = ref.watch(myDevicesProvider); + final list = devices.valueOrNull ?? + (devices.isLoading + ? ref.watch(_cachedMyDevicesProvider).valueOrNull + : null) ?? + const []; if (list.isEmpty) return null; final selectedSn = ref.watch(selectedDeviceSnOverrideProvider); for (final device in list) { diff --git a/lib/features/device/data/device_repository_impl.dart b/lib/features/device/data/device_repository_impl.dart index 73f1b9c..d80ec07 100644 --- a/lib/features/device/data/device_repository_impl.dart +++ b/lib/features/device/data/device_repository_impl.dart @@ -21,6 +21,16 @@ class DeviceRepositoryImpl implements DeviceRepository { @override Future unbindDevice(String sn) => _api.unbindDevice(sn); + @override + Future> getCachedMyDevices() => _api.getCachedMyDevices(); + + @override + Future getCachedLocation(String sn) => _api.getCachedLocation(sn); + + @override + Future> getCachedRecentScreenshots(String sn) => + _api.getCachedRecentScreenshots(sn); + @override Future getDeviceInfo(String sn) => _api.getDeviceInfo(sn); diff --git a/lib/features/device/domain/device_repository.dart b/lib/features/device/domain/device_repository.dart index db82a08..769ac15 100644 --- a/lib/features/device/domain/device_repository.dart +++ b/lib/features/device/domain/device_repository.dart @@ -7,6 +7,10 @@ abstract class DeviceRepository { /// 当前用户已绑定的设备列表。 Future> getMyDevices(); + Future> getCachedMyDevices(); + Future getCachedLocation(String sn); + Future> getCachedRecentScreenshots(String sn); + /// 绑定设备(手动输入 SN 或扫码获取 SN)。 /// /// 成功返回 null;失败返回错误提示。 diff --git a/lib/features/home/presentation/home_page.dart b/lib/features/home/presentation/home_page.dart index 742fb0f..6c12fa0 100644 --- a/lib/features/home/presentation/home_page.dart +++ b/lib/features/home/presentation/home_page.dart @@ -66,16 +66,13 @@ class _HomePageState extends State { ]; return PopScope( - // 拦截系统返回键:若在非「首页」Tab 则跳回首页;若在首页则弹出退出确认。 + // 拦截系统返回键:若在非「首页」Tab 则跳回首页;若在首页则退到桌面。 canPop: false, onPopInvokedWithResult: (didPop, _) async { if (didPop) return; if (navigationShell.currentIndex == 0) { - final shouldExit = await _showExitConfirm(context); - if (shouldExit == true) { - await SystemUiUtil.moveToBack(); - } + await SystemUiUtil.moveToBack(); } else { navigationShell.goBranch(0); } @@ -157,27 +154,4 @@ class _HomePageState extends State { ), ); } - - /// 弹出「确认退出应用」对话框。 - Future _showExitConfirm(BuildContext context) { - final l10n = AppLocalizations.of(context); - return showCupertinoDialog( - context: context, - builder: (_) => CupertinoAlertDialog( - title: Text(l10n.exitConfirmTitle), - content: Text(l10n.exitConfirmContent), - actions: [ - CupertinoDialogAction( - child: Text(l10n.cancel), - onPressed: () => Navigator.of(context).pop(false), - ), - CupertinoDialogAction( - isDestructiveAction: true, - child: Text(l10n.exitApp), - onPressed: () => Navigator.of(context).pop(true), - ), - ], - ), - ); - } } diff --git a/lib/features/home/presentation/home_tab.dart b/lib/features/home/presentation/home_tab.dart index 75d8afe..c5d5b06 100644 --- a/lib/features/home/presentation/home_tab.dart +++ b/lib/features/home/presentation/home_tab.dart @@ -662,19 +662,7 @@ class HomeTab extends ConsumerWidget { label: l10n.cfMirror, size: 50, iconSize: 20, - // 远程控制:静默触发设备端启动屏幕采集(HTTP mirror 命令,不弹窗), - // 直接进入 WebRTC 远程控制页建立实时画面与控制。 - onTap: () async { - if (sn != null && sn.isNotEmpty) { - // 静默下发 mirror,触发设备端启动屏幕采集;失败也不阻断进入控制页 - await ref - .read(deviceRepositoryProvider) - .sendDeviceOp(sn, 'mirror'); - } - if (context.mounted) { - context.push('/connection'); - } - }, + onTap: () => context.push('/connection'), ), ), Expanded( @@ -811,7 +799,10 @@ class _LocationCard extends ConsumerWidget { final locationAsync = sn == null ? const AsyncValue.data(null) : ref.watch(deviceLocationProvider(sn)); - final location = locationAsync.valueOrNull; + final location = locationAsync.valueOrNull ?? + (sn != null && locationAsync.isLoading && !locationAsync.hasValue + ? ref.watch(cachedDeviceLocationProvider(sn)).valueOrNull + : null); final locating = locationAsync.isLoading; final hasAddress = location?.displayAddress.isNotEmpty == true; @@ -920,10 +911,10 @@ class _LocationCard extends ConsumerWidget { borderRadius: BorderRadius.circular(10), ), child: Text( - locating - ? '📍 ${l10n.homeLocating}…' - : (hasAddress - ? '📍 ${location!.displayAddress}' + hasAddress + ? '📍 ${location!.displayAddress}' + : (locating + ? '📍 ${l10n.homeLocating}…' : '📍 ${l10n.homeAddress}'), style: TextStyle(fontSize: 12, color: DarkMode.color(context, AppColors.ink)), maxLines: 2, @@ -977,9 +968,13 @@ class _ScreenshotsCard extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final l10n = AppLocalizations.of(context); final sn = ref.watch(selectedDeviceSnProvider); - final screenshots = sn == null + final latest = sn == null ? const AsyncValue>.data([]) : ref.watch(recentScreenshotsProvider(sn)); + final cached = sn != null && latest.isLoading && !latest.hasValue + ? ref.watch(cachedRecentScreenshotsProvider(sn)).valueOrNull + : null; + final screenshots = cached == null ? latest : AsyncData(cached); return CardBox( child: Column(