美文网首页
Flutter 项目版本更新逻辑

Flutter 项目版本更新逻辑

作者: 卢融霜 | 来源:发表于2022-08-15 17:06 被阅读0次
版本升级弹窗.png

android 根据传入intentUrl 自动下载,跳转安装,iOS根据intentUrl跳转App Store

class AppUpdateUtils {
  static checkAppUpdate() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    HttpResponse response = await API.getSysUpdateInfo(
        updateVersion: '${packageInfo.version}',
        updatePlatform: Platform.operatingSystem,
        updateVersionCode: '${packageInfo.buildNumber}');
    if (!response.ok) {
      return;
    }
    UpdateEntity updateEntity = UpdateEntity.fromJson(response.data);
    if (!updateEntity.versionConsistency) {
      //版本不一致 更新版本
      Get.dialog(
          DialogUploadBody(
            intentUrl: "${updateEntity.downloadJumpUrl}",
            updateContent: "${updateEntity.updateContent}",
            version: '${updateEntity.updateVersion}',
            showCancel: updateEntity.updateForce == "1" ? false : true,
          ),
          barrierDismissible: false);
    }
  }
}

class DialogUploadBody extends StatefulWidget {
  final String version;
  final String updateContent;
  final bool showCancel;
  final String intentUrl;

  const DialogUploadBody(
      {required this.version,
      required this.updateContent,
      this.showCancel = true,
      required this.intentUrl,
      Key? key})
      : super(key: key);

  @override
  State<DialogUploadBody> createState() => _DialogUploadBodyState();
}

class _DialogUploadBodyState extends State<DialogUploadBody> {
  bool uploading = false;
  bool dowOk = false;
  double progress = 0.0;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return false;
      },
      child: Center(
        child: Padding(
          padding: EdgeInsets.only(left: 37.5.r, right: 37.5.r),
          child: SizedBox(
            width: double.infinity,
            child: Container(
              decoration: ShapeDecoration(
                  color: Colors.white,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.r)))),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 150.r,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        ImageView(AppAssets.upload_bg,
                            width: double.infinity,
                            cornerRadius: 10.r,
                            height: 150.r,
                            fit: BoxFit.cover),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            TU.text("版 本 更 新",
                                bold: true,
                                fs: TU.fontSize_30,
                                color: Colors.white),
                            Container(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 20.r, vertical: 2.r),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(100.r)),
                              margin: EdgeInsets.only(top: 10.r),
                              child: TU.d15("V${widget.version}",
                                  bold: true, color: TCS.blue00b6),
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                  SU.only(
                      top: 15.r,
                      bottom: 35.r,
                      left: 15.r,
                      right: 15.r,
                      child: Container(
                        constraints: BoxConstraints(maxHeight: Get.height / 2),
                        child: SingleChildScrollView(
                          child: TU.text("${widget.updateContent}",
                              height: 2, fs: TU.fontSize_15),
                        ),
                      )),
                  uploading
                      ? SU.only(
                          bottom: 10.r,
                          right: 10.r,
                          left: 10.r,
                          child: GFProgressBar(
                            percentage: progress,
                            radius: 10.r,
                            progressBarColor: TCS.blue00b6,
                          ))
                      : SizedBox(),
                  uploading
                      ? SU.only(
                          bottom: 20.r,
                          right: 10.r,
                          left: 10.r,
                          child: Align(
                              child: TU.d15(
                                  "${(progress * 100.0).toStringAsFixed(1)}%"),
                              alignment: Alignment.center))
                      : SizedBox(),
                  dowOk
                      ? SU.only(
                          left: 20.r,
                          right: 20.r,
                          bottom: 10.r,
                          child: SizedBox(
                            width: double.infinity,
                            child: TextButton(
                              onPressed: () => toInstall(),
                              child: TU.w18("立即安装"),
                              style: ButtonStyle(
                                  shape: MaterialStateProperty.all(
                                      RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(36.r))),
                                  backgroundColor:
                                      MaterialStateProperty.all(TCS.blue00b6)),
                            ),
                          ))
                      : SizedBox(),
                  !uploading
                      ? SU.only(
                          left: 20.r,
                          right: 20.r,
                          child: SizedBox(
                            width: double.infinity,
                            child: TextButton(
                              onPressed: () => toUpdate(),
                              child: TU.w18("立即升级"),
                              style: ButtonStyle(
                                  shape: MaterialStateProperty.all(
                                      RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(36.r))),
                                  backgroundColor:
                                      MaterialStateProperty.all(TCS.blue00b6)),
                            ),
                          ))
                      : SizedBox(),
                  !uploading
                      ? SU.only(
                          left: 20.r,
                          right: 20.r,
                          bottom: 10.r,
                          child: SizedBox(
                            width: double.infinity,
                            child: widget.showCancel
                                ? TextButton(
                                    onPressed: () {
                                      Get.back();
                                    },
                                    child: TU.gray18("暂不升级"),
                                    style: ButtonStyle(
                                        shape: MaterialStateProperty.all(
                                            RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(
                                                        36.r))),
                                        backgroundColor:
                                            MaterialStateProperty.all(
                                                Colors.white)),
                                  )
                                : TU.gray18(""),
                          ))
                      : SizedBox()
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  ///立即安装
  toInstall() async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = "${directory.path}/${widget.version}_.apk";
    File file = new File(path);
    if (file.existsSync()) {
      try {
        AppInstaller.installApk(path);
      } catch (e) {
        setState(() {
          ET.err("保存失败,请重试");
          uploading = false;
          dowOk = false;
        });
      }
    }
  }

  void toUpdate() async {
    if (Platform.isAndroid) {
      if (!await PHUS.storage) {
        ET.err("未获取到权限,不能进行更新");
        return;
      }
      if (!await PHUS.requestInstallPackages) {
        ET.err("未获取到权限,不能进行更新");
        return;
      }
      setState(() {
        uploading = true;
      });
      Directory directory = await getApplicationDocumentsDirectory();
      String path = "${directory.path}/${widget.version}_.apk";
      re.Response response = await Dio().download(widget.intentUrl, path,
          onReceiveProgress: (int count, int total) {
        setState(() {
          if (!uploading) {
            uploading = true;
          }
          progress = (Decimal.parse("${count}") / Decimal.parse("${total}"))
              .toDouble();
        });
      });

      if (response.statusCode == 200) {
        try {
          setState(() {
            dowOk = true;
          });
          AppInstaller.installApk(path);
        } catch (e) {
          setState(() {
            ET.err("保存失败,请重试");
            uploading = false;
            dowOk = false;
          });
        }
      } else {
        setState(() {
          ET.err("下载失败,请重试");
          uploading = false;
        });
      }
    } else if (Platform.isIOS) {
      AppInstaller.goStore("", widget.intentUrl);
    } else {
      ET.err("暂无兼容版本信息,请重试");
    }
  }
}

相关文章

网友评论

      本文标题:Flutter 项目版本更新逻辑

      本文链接:https://www.haomeiwen.com/subject/tzllgrtx.html