提交 f01f7c6d authored 作者: 史晓晨's avatar 史晓晨

feat:优化代码

上级 4ae8e1af
差异被折叠。
class Constants {
static const spCurrentDay = "current_day";
static const dateFormat = "yyyy-MM-dd";
static const ossEndpoint = 'oss-cn-beijing.aliyuncs.com';
static const ossBucketName = 'clx-prod';
}
class ServerApi {
/// ==================== 老马上来 ====================
// 获取版本号
static const String getSystemVersionByNumber =
"/user-service/system/version/getSystemVersionByNumber";
/// ==================== 项目管理工具 ====================
// 项目管理工 具 版本检测接口
static const getLatestByProductCodePM =
"/pm-process/external/web/onlineConfig/getLatestByProductCode";
// 项目管理工具 获取信息版本详情
static const getDetailPM = "/pm-process/external/web/onlineConfig/getDetail";
/// ==================== OSS工具 ====================
// 获取OSS 下载授权ak sk token
static const String generateByExt = "/msl-document/common/oss/generateByExt";
}
/// name : ""
/// content : ""
/// versionForce : true
/// versionPath : ""
class VersionInfo {
VersionInfo({
this.name,
this.content,
this.versionForce,
this.versionPath,
});
VersionInfo.fromJson(dynamic json) {
name = json['name'];
content = json['content'];
versionForce = json['versionForce'];
versionPath = json['versionPath'];
}
String? name;
String? content;
bool? versionForce;
String? versionPath;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['name'] = name;
map['content'] = content;
map['versionForce'] = versionForce;
map['versionPath'] = versionPath;
return map;
}
}
import 'dart:convert';
import 'package:apk_update/core/common/version_info.dart';
import 'package:apk_update/core/services/version_service/version_service.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import '../../../utils/dio_update_util.dart';
import '../../../utils/toast_util.dart';
import '../../common/constants.dart';
/// 承运
class CarrierVersionServices implements VersionService {
/// 网络全路径
final String url;
/// 请求头
final Map<String, dynamic>? header;
/// 请求参数
final Map<String, dynamic>? params;
/// 一天提示一次升级标识
final bool onceDay;
const CarrierVersionServices({
required this.url,
this.params,
this.header,
this.onceDay = false,
});
@override
Future<VersionInfo?> checkVersion() async {
var result =
await DioUpdateUtil.get(url, queryParameters: params, headers: header);
//获取当前时间
String spCurrent = SpUtil.getString(Constants.spCurrentDay) ?? "";
String current =
DateUtil.formatDate(DateTime.now(), format: Constants.dateFormat);
//一天提示一次升级 & 非强升 & 当天已提示 => 不再提示
if (onceDay && result?['versionForce'] == 0 && spCurrent == current) {
// 不再提示
return null;
}
//缓存当前时间
SpUtil.putString(Constants.spCurrentDay, current);
// 一天提示一次升级,是在应用首次设置,不需要提示最新版本toast
if (!onceDay && result == null) {
// 当前已经是最新版本
ToastUtil.showToast("已经是最新版本了!");
return null;
}
if (result == null) {
// 无升级任务,拦截
return null;
}
// 返回升级版本信息
return VersionInfo(
name: result['versionName'],
content: result['tipContent'] ?? result['versionContent'],
versionForce: result['versionForce'] == 1,
versionPath: result['versionPath'],
);
}
}
import 'dart:convert';
import 'package:apk_update/core/common/version_info.dart';
import 'package:apk_update/core/services/version_service/version_service.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import '../../../utils/dio_update_util.dart';
import '../../../utils/toast_util.dart';
import '../../common/constants.dart';
/// 老马上来
class MSLVersionServices implements VersionService {
/// 网络全路径
final String url;
/// 请求头
final Map<String, dynamic>? header;
/// 请求参数
final Map<String, dynamic>? params;
/// 一天提示一次升级标识
final bool onceDay;
const MSLVersionServices({
required this.url,
this.params,
this.header,
this.onceDay = false,
});
@override
Future<VersionInfo?> checkVersion() async {
var result =
await DioUpdateUtil.get(url, queryParameters: params, headers: header);
//获取当前时间
String spCurrent = SpUtil.getString(Constants.spCurrentDay) ?? "";
String current =
DateUtil.formatDate(DateTime.now(), format: Constants.dateFormat);
//一天提示一次升级 & 非强升 & 当天已提示 => 不再提示
if (onceDay && result?['versionForce'] == 0 && spCurrent == current) {
// 不再提示
return null;
}
//缓存当前时间
SpUtil.putString(Constants.spCurrentDay, current);
// 一天提示一次升级,是在应用首次设置,不需要提示最新版本toast
if (!onceDay && result == null) {
// 当前已经是最新版本
ToastUtil.showToast("已经是最新版本了!");
return null;
}
if (result == null) {
// 无升级任务,拦截
return null;
}
// 返回升级版本信息
return VersionInfo(
name: result['versionName'],
content: result['tipContent'] ?? result['versionContent'],
versionForce: result['versionForce'] == 1,
versionPath: result['versionPath'],
);
}
}
import 'dart:convert';
import 'package:apk_update/core/common/version_info.dart';
import 'package:apk_update/core/services/version_service/version_service.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import '../../../utils/dio_update_util.dart';
import '../../../utils/toast_util.dart';
import '../../common/constants.dart';
import '../../common/servier_api.dart';
/// 项目管理工具
class PMVersionServices implements VersionService {
/// 域名
final String baseUrl;
/// 请求头
final Map<String, dynamic>? header;
/// 请求参数
final Map<String, dynamic>? params;
/// 一天提示一次升级标识
final bool onceDay;
const PMVersionServices({
required this.baseUrl,
this.params,
this.header,
this.onceDay = false,
});
@override
Future<VersionInfo?> checkVersion() async {
// ①版本检测
var checkResult = await checkVersionPM();
// ②获取版本详情
var result = await getVersionDetailPM(checkResult?['id']);
// 返回升级版本信息
return VersionInfo(
name: result['name'],
content: result['popContent'],
versionForce: result['forceUpgradeStatus'] == 1,
versionPath: result['versionPath'],
);
}
/// 版本检测
Future<dynamic> checkVersionPM() async {
var checkResult = await DioUpdateUtil.get(
"$baseUrl${ServerApi.getLatestByProductCodePM}",
queryParameters: params,
headers: header);
// 是否是最新版本提示
final newVersion =
int.tryParse(checkResult?['version']?.toString() ?? '') ?? 0;
final currentVersion =
int.tryParse(params?["currentVersion"]?.toString() ?? '') ?? 0;
if (newVersion <= currentVersion) {
if (!onceDay) {
ToastUtil.showToast('已经是最新版本了!');
}
return null;
}
return checkResult;
}
/// 获取版本详情
Future<dynamic> getVersionDetailPM(int? id) async {
var detailResult = await DioUpdateUtil.get(
"$baseUrl${ServerApi.getDetailPM}",
queryParameters: {'id': id},
headers: header);
// 是否是最新版本提示
final newVersion =
int.tryParse(detailResult?['version']?.toString() ?? '') ?? 0;
final currentVersion =
int.tryParse(params?["currentVersion"]?.toString() ?? '') ?? 0;
if (newVersion <= currentVersion) {
if (!onceDay) {
ToastUtil.showToast('已经是最新版本了!');
}
return null;
}
return detailResult;
}
}
import 'package:apk_update/core/common/version_info.dart';
import '../../../utils/connectivity_util.dart';
import '../../../utils/toast_util.dart';
/// 版本检测接口
abstract class VersionService {
/// 版本检测
Future<VersionInfo?> _checkVersion() async {
// 判断网络是否连接
var resList = await connectivity.checkConnectivity();
if (resList.isNotEmpty && resList[0] == ConnectivityResult.none) {
ToastUtil.showToast("网络异常,请检查网络");
return null;
}
return await checkVersion();
}
Future<VersionInfo?> checkVersion();
}
// import 'dart:convert';
//
// import 'package:apk_update/utils/connectivity_util.dart';
// import 'package:apk_update/utils/toast_util.dart';
// import 'package:apk_update/widget/update_dialog.dart';
// import 'package:dio/dio.dart';
// import 'package:flustars_flutter3/flustars_flutter3.dart';
// import 'package:get/route_manager.dart';
// import '../../core/common/constants.dart';
// import '../../core/common/servier_api.dart';
//
// /// 获取更新版本信息
// /// url 请求地址
// /// versionNumber 当前应用versionCode
// /// productNo 产品号
// /// onceDay 一天提示一次(应用首页设置true)
// void checkVersion(
// {required String url,
// required Method method,
// Map<String, dynamic>? params,
// Map<String, dynamic>? header,
// bool onceDay = false,
// Function()? jumpAppStore, // 跳转AppStore
// Function(String? path)? installApk, // 安装Apk
// Function()? downloadApkError, // 下载Apk错误
// Function(String? path, String? apkPath)? downloadApk, // 使用OSS下载Apk
// int? isOssDownload //1 使用OSS下载
// }) async {
//
//
// try {
// final Response response = await DioUpdateUtil.getDio().request(
// url,
// options: Options(method: method.value, headers: header),
// queryParameters: params,
// data: params,
// );
// // 网络请求成功
// printLog(response); // 打印日志
// var responseData = response.data;
// if (responseData.runtimeType == String) {
// // 兼容后端数据返回string
// responseData = json.decode(responseData);
// }
// if (responseData?["code"] != 0) {
// ToastUtil.showToast(responseData?["msg"]);
// return;
// }
// var result = responseData?["data"];
// //获取当前时间
// String spCurrent = SpUtil.getString(Constants.spCurrentDay) ?? "";
// String current = DateUtil.formatDate(DateTime.now(), format: Constants.dateFormat);
// //一天提示一次升级 & 非强升 & 当天已提示 => 不再提示
// if (onceDay && result?['versionForce'] == 0 && spCurrent == current) {
// // 不再提示
// return;
// }
// //缓存当前时间
// SpUtil.putString(Constants.spCurrentDay, current);
// // 一天提示一次升级,是在应用首次设置,不需要提示最新版本toast
// if (!onceDay && result == null) {
// // 当前已经是最新版本
// ToastUtil.showToast("已经是最新版本了!");
// return;
// }
// if (result == null) {
// // 无升级任务,拦截
// return;
// }
// // 升级弹框提示
// Get.dialog(
// UpdateDialog(
// title: result['versionName'],
// content: result['tipContent'] ?? result['versionContent'],
// versionForce: result['versionForce'] == 1,
// versionPath: result['versionPath'],
// jumpAppStore: jumpAppStore,
// installApk: installApk,
// isOssDownload: isOssDownload,
// downloadApk: downloadApk,
// downloadApkError: downloadApkError,
// ),
// );
// } on DioException catch (e) {
// printLog(e.response); // 打印日志
// ToastUtil.showToast("服务器请求错误");
// }
// }
//
// /// 检查版本(项目管理工具)
// void checkVersionPM(
// {required String baseUrl,
// Map<String, dynamic>? params,
// bool onceDay = false,
// Function()? jumpAppStore, // 跳转AppStore
// Function(String? path)? installApk, // 安装Apk
// Function()? downloadApkError, // 下载Apk错误
// Function(String? path, String? apkPath)? downloadApk, // 使用OSS下载Apk
// int? isOssDownload //1 使用OSS下载
// }) async {
// // 判断网络是否连接
// var resList = await connectivity.checkConnectivity();
//
// if (resList.isNotEmpty && resList[0] == ConnectivityResult.none) {
// ToastUtil.showToast("网络异常,请检查网络");
// return;
// }
//
// try {
// final Response response = await DioUpdateUtil.getDio().request(
// "$baseUrl${ServerApi.getLatestByProductCodePM}",
// options: Options(
// method: Method.get.value, headers: {"productGroupCode": "common"}),
// queryParameters: params,
// );
// // 网络请求成功
// printLog(response); // 打印日志
// var responseData = response.data;
// if (responseData.runtimeType == String) {
// // 兼容后端数据返回string
// responseData = json.decode(responseData);
// }
// if (responseData?["code"] != 0) {
// ToastUtil.showToast(responseData?["msg"]);
// return;
// }
// var result = responseData?["data"];
// // 是否是最新版本提示
// final newVersion = int.tryParse(result?['version']?.toString() ?? '') ?? 0;
// final currentVersion =
// int.tryParse(params?["currentVersion"]?.toString() ?? '') ?? 0;
// if (newVersion <= currentVersion) {
// if (!onceDay) {
// ToastUtil.showToast('已经是最新版本了!');
// }
// return;
// }
// // 获取新版本详情
// getVersionDetailPM(
// baseUrl: baseUrl,
// id: result?['id'],
// onceDay: onceDay,
// versionNumber: params?["currentVersion"],
// jumpAppStore: jumpAppStore,
// installApk: installApk,
// downloadApkError: downloadApkError,
// downloadApk: downloadApk,
// isOssDownload: isOssDownload,
// );
// } on DioException catch (e) {
// printLog(e.response); // 打印日志
// ToastUtil.showToast("服务器请求错误");
// }
// }
//
// /// 获取版本详情(项目管理工具)
// void getVersionDetailPM({
// required String baseUrl,
// required int? id,
// required bool onceDay,
// required int? versionNumber,
// Function()? jumpAppStore, // 跳转AppStore
// Function(String? path)? installApk, // 安装Apk
// Function()? downloadApkError, // 下载Apk错误
// Function(String? path, String? apkPath)? downloadApk, // 使用OSS下载Apk
// int? isOssDownload, //1 使用OSS下载
// }) async {
// // 判断网络是否连接
// var resList = await connectivity.checkConnectivity();
//
// if (resList.isNotEmpty && resList[0] == ConnectivityResult.none) {
// ToastUtil.showToast("网络异常,请检查网络");
// return;
// }
//
// try {
// final Response response = await DioUpdateUtil.getDio().request(
// "$baseUrl${ServerApi.getDetailPM}",
// options: Options(method: Method.get.value, headers: {
// 'productGroupCode': 'common',
// }),
// queryParameters: {'id': id},
// );
// // 网络请求成功
// printLog(response); // 打印日志
// var responseData = response.data;
// if (responseData.runtimeType == String) {
// // 兼容后端数据返回string
// responseData = json.decode(responseData);
// }
// if (responseData?["code"] != 0) {
// ToastUtil.showToast(responseData?["msg"]);
// return;
// }
// var result = responseData?["data"];
// //获取当前时间
// String spCurrent = SpUtil.getString(Constants.spCurrentDay) ?? "";
// String current = DateUtil.formatDate(DateTime.now(), format: Constants.dateFormat);
// // 是否是强升
// final versionForce = result?['forceUpgradeStatus'] == 1;
// //一天提示一次升级 & 非强升 & 当天已提示 => 不再提示
// if (onceDay && !versionForce && spCurrent == current) {
// // 不再提示
// return;
// }
// //缓存当前时间
// SpUtil.putString(Constants.spCurrentDay, current);
// // 一天提示一次升级,是在应用首次设置,不需要提示最新版本toast
// if (!onceDay && result == null) {
// // 当前已经是最新版本
// ToastUtil.showToast("已经是最新版本了!");
// return;
// }
// // 是否是最新版本提示
// final newVersion = int.tryParse(result?['version']?.toString() ?? '') ?? 0;
// final currentVersion = int.tryParse(versionNumber?.toString() ?? '') ?? 0;
// if (newVersion <= currentVersion) {
// if (!onceDay) {
// ToastUtil.showToast('已经是最新版本了!');
// }
// return;
// }
//
// // 升级弹框提示
// Get.dialog(
// UpdateDialog(
// title: result['name'],
// content: result['popContent'],
// versionForce: result['forceUpgradeStatus'] == 1,
// versionPath: result['versionPath'],
// jumpAppStore: jumpAppStore,
// installApk: installApk,
// isOssDownload: isOssDownload,
// downloadApk: downloadApk,
// downloadApkError: downloadApkError,
// ),
// );
// } on DioException catch (e) {
// printLog(e.response); // 打印日志
// ToastUtil.showToast("服务器请求错误");
// }
// }
\ No newline at end of file
import 'dart:convert';
import 'package:apk_update/utils/toast_util.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
export 'package:dio/dio.dart'; import 'package:flutter/material.dart';
class DioUpdateUtil { class DioUpdateUtil {
// dio 单例对象 static final Dio _dio = _initDio();
static final Dio _dio = Dio();
DioUpdateUtil._internal();
static Dio get dio => _dio;
static Dio _initDio() {
final dio = Dio();
// 基础配置
dio.options = BaseOptions(
connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 15),
contentType: Headers.jsonContentType,
responseType: ResponseType.plain);
dio.interceptors.add(LogInterceptor(
requestBody: true,
responseBody: true,
));
return dio;
}
static Dio getDio() { // GET请求
return _dio; static Future<dynamic> get(
String path, {
Map<String, dynamic>? queryParameters,
Map<String, dynamic>? headers,
}) async {
try {
final Response response = await _dio.get(
path,
queryParameters: queryParameters,
options: Options(headers: headers),
);
return successCallbackHandler(response);
} on DioException catch (e) {
debugPrint(e.message);
return null;
}
}
// POST请求
static Future<dynamic> post(
String path, {
dynamic data,
Map<String, dynamic>? queryParameters,
Map<String, dynamic>? headers,
}) async {
try {
final Response response = await _dio.post(
path,
data: data,
queryParameters: queryParameters,
options: Options(headers: headers),
);
return successCallbackHandler(response);
} on DioException catch (e) {
debugPrint(e.message);
return null;
}
}
/// 请求成功处理
static dynamic successCallbackHandler(Response response) {
var responseData = response.data;
if (responseData.runtimeType == String) {
// 兼容后端数据返回string
responseData = json.decode(responseData);
}
if (responseData?["code"] != 0) {
ToastUtil.showToast(responseData?["msg"]);
return null;
}
return responseData?["data"];
} }
} }
// /// 日志打印
// void printLog(Response? response) {
// var responseData = response?.data;
// var requestOptions = response?.requestOptions;
// var headers = response?.headers;
// debugPrint("========== 网络请求响应 ==========\n"
// "statusCode:${response?.statusCode} \n"
// "statusMessage:${response?.statusMessage}\n"
// "method:${requestOptions?.method}\n"
// "path:${requestOptions?.path}\n"
// "headers:${headers?.map}\n\n"
// "queryParameters:${requestOptions?.queryParameters}\n"
// "data:${requestOptions?.data}\n"
// "responseData:$responseData\n");
// }
差异被折叠。
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论