2 changed files with 61 additions and 3 deletions
@ -0,0 +1,53 @@
|
||||
// lib/app/core/controllers/app_controller.dart (新文件) |
||||
|
||||
import 'package:flutter/material.dart'; |
||||
import 'package:get/get.dart'; |
||||
import 'package:problem_check_system/app/core/services/network_status_service.dart'; // 导入你的 Service |
||||
|
||||
class AppController extends GetxController { |
||||
final NetworkStatusService _networkStatusService = Get.find(); |
||||
|
||||
// 用于防止应用启动时就显示“已连接”的提示 |
||||
bool _isFirstCheck = true; |
||||
|
||||
@override |
||||
void onInit() { |
||||
super.onInit(); |
||||
|
||||
// [核心] 使用 GetX 的 'ever' worker 来监听 isOnline 的变化 |
||||
// ever() 会在每次 isOnline.value 改变时调用回调函数 |
||||
ever(_networkStatusService.isOnline, _showConnectivitySnackbar); |
||||
} |
||||
|
||||
void _showConnectivitySnackbar(bool isOnline) { |
||||
// 首次检查时,如果是连接状态则不提示,避免打扰 |
||||
if (_isFirstCheck) { |
||||
_isFirstCheck = false; |
||||
if (isOnline) { |
||||
return; // 启动时在线,静默处理 |
||||
} |
||||
} |
||||
|
||||
// 根据网络状态显示不同的 SnackBar |
||||
if (!isOnline) { |
||||
Get.snackbar( |
||||
'网络断开', |
||||
'请检查您的网络连接', |
||||
backgroundColor: Colors.red[400], |
||||
colorText: Colors.white, |
||||
icon: const Icon(Icons.wifi_off, color: Colors.white), |
||||
duration: const Duration(seconds: 5), // 网络断开时提示时间更长 |
||||
); |
||||
} else { |
||||
// 只有在非首次检查时(即从断开恢复到连接时)才提示 |
||||
Get.snackbar( |
||||
'网络已连接', |
||||
'您现在已恢复在线状态', |
||||
backgroundColor: Colors.green[400], |
||||
colorText: Colors.white, |
||||
icon: const Icon(Icons.wifi, color: Colors.white), |
||||
duration: const Duration(seconds: 3), |
||||
); |
||||
} |
||||
} |
||||
} |
||||
Loading…
Reference in new issue