check method

Future<void> check(
  1. BuildContext context, {
  2. required String url,
  3. UpdateAvailableCallback? onUpdateAvailable,
  4. Map<String, dynamic>? params,
})

检查更新

context - BuildContext,用于显示对话框 url - 检查更新的API地址 params - API请求参数

Implementation

Future<void> check(
  BuildContext context, {
  required String url,
  UpdateAvailableCallback? onUpdateAvailable,
  Map<String, dynamic>? params,
}) async {
  _log('开始检查更新...');
  try {
    final response = await _dio.get(url, queryParameters: params);
    if (response.statusCode != 200) {
      throw "网络请求失败,状态码: ${response.statusCode}";
    }

    _log('检查更新成功,开始解析数据: ${response.data}');
    final newVersionInfo = await _parser(response.data);
    final packageInfo = await PackageInfo.fromPlatform();
    final currentVersion = packageInfo.version;
    _log('获得旧版本信息 $currentVersion');
    _updateInfo = UpdateInfo(currentVersion: currentVersion, latestVersion: newVersionInfo);

    if (newVersionInfo.version != currentVersion) {
      _hasUpdate = true;
    } else {
      if (newVersionInfo.buildVersion != packageInfo.buildNumber) {
        _hasUpdate = true;
      }
    }

    // 简单比较版本号,可根据需要替换为更复杂的比较逻辑
    if (_hasUpdate) {
      _log('发现新版本: ${_updateInfo!.latestVersion!.version}');
      statusNotifier.value = DownloadStatus.none; // 重置状态
      progressNotifier.value = 0.0; // 重置进度

      // 优先使用回调
      if (onUpdateAvailable != null) {
        onUpdateAvailable(context, _updateInfo!);
      }
      // 若回调为空,则使用弹出框
      else if (_dialogBuilder != null) {
        showDialog(
          context: context,
          barrierDismissible: newVersionInfo.updateStatus == 2,
          builder: (ctx) => _dialogBuilder!(ctx, _updateInfo!, statusNotifier, progressNotifier),
        );
      } else {
        _log('警告: 未设置 dialogBuilder 和 onUpdateAvailable 回调,将不会有任何更新提示。');
      }
    } else {
      _log('当前已是最新版本。');
    }
  } catch (e) {
    _log('检查更新时出错: $e');
    _errorHandler?.call(e);
  }
}