You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.2 KiB

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../../../data/models/user_Info.dart';
import '../../../routes/app_routes.dart';
import '../../../core/themes/theme_service.dart';
import '../../../data/services/network/api.dart';
class SplashController extends GetxController {
final GetStorage _storage = GetStorage();
// 进度条动画控制
final _loadingProgress = 0.0.obs;
double get loadingProgress => _loadingProgress.value;
// 资源加载状态
final _isResourceLoaded = false.obs;
bool get isResourceLoaded => _isResourceLoaded.value;
// 版本号
final String version = 'v1.0.0';
// 主题服务
final ThemeService _themeService = ThemeService();
@override
void onInit() {
super.onInit();
WidgetsBinding.instance.addPostFrameCallback((_) {
_startLoadingAnimation();
_loadAppResources();
});
}
// 进度条动画(持续2秒)
void _startLoadingAnimation() {
const totalDuration = 2000; // 动画总时长2秒
const steps = totalDuration ~/ 50; // 40次更新(50ms间隔)
final stepValue = 1.0 / steps;
Timer.periodic(const Duration(milliseconds: 50), (timer) {
if (_loadingProgress.value < 1.0) {
_loadingProgress.value += stepValue;
} else {
timer.cancel();
_checkNavigateCondition();
}
});
}
// 异步加载应用资源
Future<void> _loadAppResources() async {
try {
// 模拟资源加载(如API配置、本地缓存等)
await Future.delayed(const Duration(milliseconds: 1500));
// 实际资源加载代码
// await _loadImages();
// await _initDatabase();
_isResourceLoaded.value = true;
_checkNavigateCondition();
} catch (e) {
Get.snackbar('错误', '资源加载失败,请检查网络连接');
_isResourceLoaded.value = true; // 允许用户继续使用
print('资源加载错误: $e');
}
}
// 检查跳转条件
void _checkNavigateCondition() {
if (_loadingProgress.value >= 1.0 && _isResourceLoaded.value) {
_navigateToLogin();
}
}
// 获取登录Token并跳转
Future<void> _navigateToLogin() async {
final isLoggedIn = await getLoginToken();
if (isLoggedIn) {
// Get.offAllNamed(Routes.login); // 跳转到登录页
// Get.offAllNamed(Routes.home); // 跳转到主页
Get.offAllNamed(Routes.pairing);
} else {
Get.offAllNamed(Routes.login); // 跳转到登录页
}
}
Future<bool> getLoginToken() async {
try {
print('getLoginToken:进来了');
//if (User.getname() != "") {
final response = await Api.tokenlogin();
print('getLoginToken: $response');
if (response == null) return false;
if (response['user'] != '') {
print('getLoginToken:进来了');
// 根据API设计调整
final user = User.fromJson(response);
// 存储用户信息(示例)
await _storage.write('user_info', user.toJson());
return true;
}
//return true;
//}
return false;
} catch (e) {
print('Token获取失败: $e');
return false;
}
}
}