Flutter APP升级功能模块分享

实现功能

  • 自动检查本地APP版本是否最新
  • 自动提醒用户升级
  • 引导用户去 AppStore 或 Google Play 市场完成升级操作
  • 当用户放弃本次升级后,在1天内不再提醒

实现逻辑

![业务逻辑](https://raw.githubusercontent.com/tongweizj/MaxFlutterTutorial/master/doc/img/max-flutter-tutorial-1.png “Image title” %}

业务功能截图

目录结构

1
2
3
4
5
6
7
8
9
10
11
12
.
├── lib
│ ├── main.dart
│ ├── setting.dart
│ ├── core
│ │ ├── service
│ │ └── viewmodels
│ └── ui
│ ├── home_view.dart
│ ├── updater_view.dart
│ └── widgets
└── pubspec.yaml

核心代码片段说明

update_view.dart

在启动页或某个必须经过的页面上加入update_view,
用异步的方式调用升级检查功能,如果可以升级,就在当前页面插入ShowDialog

1
2
3
4
5
6
7
/// update_view.dart
_isUpdate() async {
var isUpdate = await UpdateModel.isUpdate();
if (isUpdate["isUpdate"] == 1) {
buildUpdateShowDialog(context, isUpdate["appStoreUrl"]);
}
}

update_model.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class UpdateModel {
/// 检查是否需要升级
static Future isUpdate() async {
// changeState(ViewState.Busy);
//每次打开APP获取当前时间戳
var timeEnd = DateTime.now().millisecondsSinceEpoch;
//获取"Later"保存的时间戳
var timeStart = UpdateApi.getUpgradeRemindLaterTime();

if (timeStart == 0 && timeEnd - timeStart >= getUpdateFrequency) {
// 之前没有点击过,这事第一次打开APP时执行"版本更新"的网络请求
// 或者 间隔时间 >= 一周,执行网络请求

Map appVersionData = await UpdateApi.getAppVersion();
var respAppVer = Map.from({
"isUpdate": 1,
"appStoreUrl": "",
});
var _serviceVersionCode;
if (appVersionData != null) {
/// 判断当前用户手机系统是ios 还是 android
if (Platform.isIOS) {
// 赋值ios客户单的版本号
_serviceVersionCode = appVersionData["versionCode"]["ios"];
// 赋值ios客户端的AppStore的URL
respAppVer["appStoreUrl"] = SERVER_AppStore_URL;
} else if (Platform.isAndroid) {
//android相关代码
_serviceVersionCode = appVersionData["versionCode"]["android"];
//GooglePlay的 下载URL
respAppVer["appStoreUrl"] = SERVER_GooglePlay_URL;
}
}
/// 比较本地版本号和服务端版本号的大小
respAppVer["isUpdate"] = await _checkVersionCode(_serviceVersionCode);
return respAppVer;
}
}

//检查版本更新的版本号
static _checkVersionCode(String appSerCode) {
String _appLocalCodeStr = UpdateApi.getAppLocalCode();
final _appSerCode = Version.parse(appSerCode);
final _appLocalCode = Version.parse(_appLocalCodeStr);
if (_appSerCode > _appLocalCode) {
return 1;
} else {
return 0;
}
}
}

源代码

Github