Flutter实现APP更新

这是一个记录贴,关于flutter app内部更新网上有很多帖子,用package_info、path_provider、open_file、flutter_downloader这四个插件实现检测APP版本信息,需要更新后执行下载、安装任务~

但是小编不是专业Android开发,使用flutter_downloader的时候程序报各种错,网上各种找办法解决未果后决定放弃这个路线,当需要更新咱跳转到手机浏览器进行下载安装(嘿嘿,是不是机智的一匹~),这里主要说一下ios更新,要跳转到App Store更新~

下面上代码:

class HomePage extends StatefulWidget {
    HomePage({Key key}) : super(key: key);
    _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State {
    @override
    void initState () {
        Future.delayed(Duration(seconds: 3), (){
            _checkVersion();
        });
    }

    //我们可以在APP所处服务器上建一个version.json文件,用来保存版本信息和更新信息,每次进APP去获取里面的内容,然后和手机上APP版本比较
    void _checkVersion () async {
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        //APP的versionName
        String version = packageInfo.version;
        //APP的versionCode
        String buildNumber = packageInfo.buildNumber;
        //下面进行判断,Android还是ios
        if (Platform.isAndroid) {
            var api = "你的服务器路径/version.json";
            final res = await Dio().get(api);
            if (res.statusCode == 200) {
                //这里小编直接比较versionCode了,因为直接比较一个数字好比较
                //如果想比较versionName也可以,思路是先把字符串通过split(".")分割成一个数组,然后分别比较两个数组对应index的两个值,只要有一个小于服务器上的值就提示更新就行了
                if (int.parse(buildNumber) < int.parse(res.data["versionCode"])) {
                showDialog(
                    context: context,
                    //强制更新,不可以点击空白区域关闭,不需要可以不要
                    barrierDismissible: false,
                    builder: (BuildContext context){
                        return AlertDialog(
                            title: Text("提示!"),
                            content: Text("检测到新版本,是否更新?"),
                            actions: [
                                FlatButton(
                                    child: Text("立即更新"),
                                    onPressed: (){
                                        this._launcherApp();
                                    },
                                ),
                                FlatButton(
                                    child: Text("稍后再说"),
                                    onPressed: (){
                                        exit(0);
                                    },
                                ),
                            ],
                        );
                    }
                );
            }
        } else {
            Fluttertoast.showToast(
                msg: "服务器错误",
                gravity: ToastGravity.CENTER,
                timeInSecForIos: 3
            );
        }
    } else if (Platform.isIOS) {
        //这里比较版本可以和上面一样,小编这里版本号搞成了固定的三个数,直接转成int比较了
        version = version.replaceAll(".", "");
        //通过下面的路径获取你的APP在App Store Connect上面的版本号,截图在下面会贴上来
        //如果感觉这个方法不靠谱的朋友也可以在version.json里配上刚刚上传审核成功的APP版本号,然后和本地获取到的APPversion对比,需要更新跳转到App Store进行下载即可
        var iosApi = "https://itunes.apple.com/cn/lookup?id=这里是你的APP成功上传并审核后的ID,如何获取下面会贴";
        final res = await Dio().get(iosApi);
        //然后你就会或得一个版本号
        String oldVersion = json.decode(res.data)["results"][0]["version"];
        oldVersion = oldVersion.replaceAll(".", "");
        if (int.parse(version) < int.parse(oldVersion)) {
            showDialog(
                context: context,
                barrierDismissible: false,
                builder: (BuildContext context){
                    return AlertDialog(
                        title: Text("提示!"),
                        content: Text("检测到新版本,是否更新?"),
                        actions: [
                            FlatButton(
                                child: Text("立即更新"),
                                onPressed: (){
                                    this._launcherApp();
                                },
                            ),
                            FlatButton(
                                child: Text("稍后再说"),
                                onPressed: (){
                                    //退出程序
                                    exit(0);
                                },
                            ),
                        ],
                    );
                }
            );
         }
      }
    }

    _launcherApp () async {
        if (Platform.isAndroid) {
          var url = "你的Android apk服务器路径";
          if (await canLaunch(url)){
            await launch(url);
          } else {
            Fluttertoast.showToast(
              msg: "无法加载",
              gravity: ToastGravity.CENTER,
              timeInSecForIos: 3
            );
          }
        } else if (Platform.isIOS) {
          //ios跳转appstore更新
          var url = "https://itunes.apple.com/cn/app/id与上面的ID一样";
          if (await canLaunch(url)) {
            await launch(url);
          } else {
            Fluttertoast.showToast(
              msg: "无法加载",
              gravity: ToastGravity.CENTER,
              timeInSecForIos: 3
            );
          }
        }
      }
}

两个跳转都可以跳转,恭喜你成功了~ 

下面是几个附件:

version.json:

{
    "versionName": "1.0.0",
    "versionCode": "00",
    "versionMsg": "对系统进行了调整优化,修复bug"
}

有关App Store Connect上APP信息:

Flutter实现APP更新_第1张图片

这里就有你的APP版本号~,获取到数据后是下面这样婶儿的,

{
	"resultCount":1,
	"results": [
		{
			"appletvScreenshotUrls":[], 
			"screenshotUrls":[], 
			"ipadScreenshotUrls":[],
			"artworkUrl512":"",
			"isGameCenterEnabled":false,
			"artworkUrl60":"",
			"artworkUrl100":"",
			"artistViewUrl":"",
			"advisories":[],
			"features":[], 
			"supportedDevices":[],
			"kind":"software",
			"languageCodesISO2A":["EN"],
			"fileSizeBytes":"",
			"averageUserRatingForCurrentVersion":0,
			"userRatingCountForCurrentVersion":0,
			"trackContentRating":"4+",
			"averageUserRating":0,
			"trackViewUrl":"",
			"contentAdvisoryRating":"4+",
			"trackCensoredName":"",
			"trackId":,
			"trackName":"",
			"releaseDate":"2020-06-09T07:00:00Z",
			"genreIds":[],
			"formattedPrice":"免费",
			"primaryGenreName":"Business",
			"isVppDeviceBasedLicensingEnabled":true,
			"minimumOsVersion":"8.0",
			"sellerName":"",
			"currentVersionReleaseDate":"2020-06-09T20:55:10Z",
			"primaryGenreId":,
			"currency":"CNY",
			"description":"",
			"artistId":,
			"artistName":"",
			"genres":["商务", "工具"],
			"price":0.00,
			"bundleId":"",
                        //这个就是版本号
			"version":"1.0",
			"wrapperType":"software",
			"userRatingCount":0
		}
	]
}

下面的操作就按上面代码走了~

如何获取已上架APP的ID?

用你的iPhone打开App Store,搜索你的APP名称(上架了就会搜索到),点击进到详情里面去,你的APP图标右边有个三个小点按钮点一下,会有拷贝链接字样,拷贝后找个地方粘贴一下就能看到了!拿微信举个例子给大家截个图

Flutter实现APP更新_第2张图片

Flutter实现APP更新_第3张图片

小编刚踩坑踩出来的,有不对的地方还请大佬指点~

你可能感兴趣的:(Flutter,Dart,Android)