Flutterflutter

flutter实现APP版本更新+(全局弹窗overlay实现)

2021-02-08  本文已影响0人  _诸葛青

升级说明:
Android:应用内更新下载+安装。iOS:跳转到appstore下载安装。
注:可以通过热更新技术进行升级(我不会)。
引用插件:

  #获取当前版本
  package_info: ^0.4.3+2
  #版本内更新
  ota_update: ^2.4.1
  #网页打开工具
  url_launcher: ^5.7.10
  #事件车
  event_bus: ^1.1.1

直接上代码:

class VersionUpdate {
  ///检查是否需要更新
  ///是否需要升级--判断
  static Future<bool> isUpdating() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String localVersion = packageInfo.version;
    SpUtil.putString('localVersion', localVersion);
    ApiResponse<VersionEntity> res =
        await PersonalCenterAPI.updatingVersion(versionNo: packageInfo.version);
    if (res.status == Status.COMPLETED) {
      //如果获取服务器的版本号与当前应用程序的版本号对比,,不等那么提示升级(判断条件修改为符合自己的)
      SpUtil.putObject('netVersionInfo', res.data.toJson());
      if (res.data.currentVersion != localVersion) {
        BottomSheetDialog.overLayDialog();
      }
    }
    //return isUpdating;
  }

  ///android--去android应用内下载更新  ---ios跳去App Store
  static downloadNewVersion({String Url}) async {
    if (Platform.isIOS) {
      String url = Url;
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    } else if (Platform.isAndroid) {
      String url = Url;
      try {
        // destinationFilename 是对下载的apk进行重命名
        OtaUpdate().execute(url, destinationFilename: 'gzzoc.apk').listen(
          (OtaEvent event) {
            switch (event.status) {
              case OtaStatus.DOWNLOADING: // 下载中
                //TestEventBus().bus.fire(ProgressEvent(data: event.value));
                ProgressEventBus().bus.fire(ProgressEvents(data: event.value));
                print('status:${event.status},value:${event.value}');
                break;
              case OtaStatus.INSTALLING: //安装中
                break;
              case OtaStatus.PERMISSION_NOT_GRANTED_ERROR: // 权限错误
                print('更新失败');
                break;
              default: // 其他问题
                break;
            }
          },
        );
      } catch (e) {
        print('更新失败');
      }
    }
  }
}

overLayDialog

overLayDialog() {
    OverlayState overlayState = Application.globalKey.currentState.overlay;
    OverlayEntry overlayEntry;
    overlayEntry = new OverlayEntry(builder: (context) {
      return OverLayDialog(
        overlayEntry: overlayEntry,
      );
    });
    overlayState.insert(overlayEntry);
  }

OverLayDialog名字太像了(忘记改了)

class OverLayDialog extends StatefulWidget {
 final OverlayEntry overlayEntry;

 OverLayDialog({this.overlayEntry});

 @override
 _OverLayDialogState createState() => _OverLayDialogState();
}

class _OverLayDialogState extends State<OverLayDialog> {
 VersionEntity _netVersionInfo;
 String _progress;
 @override
 void initState() {
   // TODO: implement initState
   super.initState();
   _netVersionInfo =
       VersionEntity.fromJson(SpUtil.getObject('netVersionInfo'));
   ProgressEventBus().bus.on<ProgressEvents>().listen((event) {
     if (!mounted) return;
     setState(() {
       _progress = event.data;
     });
   });
 }

 @override
 Widget build(BuildContext context) {
   return Material(
     color: MyColors.black_cc00,
     child: Container(
         margin: EdgeInsets.symmetric(horizontal: 40),
         child: Center(
           child: Column(
             mainAxisSize: MainAxisSize.min,
             children: [
               Stack(
                 alignment: Alignment.bottomCenter,
                 children: [
                   Stack(
                     children: [
                       Image.asset(
                         'assets/images/version_update.png',
                       ),
                       Container(
                         margin: EdgeInsets.only(top: 60),
                         padding: EdgeInsets.symmetric(horizontal: 20),
                         child: Column(
                           crossAxisAlignment: CrossAxisAlignment.start,
                           children: [
                             Text(
                               '发现新版本',
                               style: TextStyle(
                                   color: MyColors.white,
                                   fontWeight: FontWeight.bold,
                                   fontSize: 21),
                             ),
                             Text('版本:${_netVersionInfo.currentVersion}',
                                 style: TextStyle(
                                     color: MyColors.white, fontSize: 16)),
                             Container(
                               height: MediaQuery.of(context).size.height / 3,
                               padding: EdgeInsets.only(top: 22, bottom: 22),
                               child: ListView.builder(
                                   // itemCount: _content.length,
                                   itemCount: _netVersionInfo?.description
                                       ?.split(';')
                                       ?.length,
                                   itemBuilder: (context, index) {
                                     return Padding(
                                       padding:
                                           EdgeInsets.symmetric(vertical: 7),
                                       child: Text(
                                         _netVersionInfo?.description
                                             ?.split(';')[index],
                                         style: TextStyle(
                                             color: MyColors.white,
                                             fontSize: 15),
                                       ),
                                     );
                                   }),
                             )
                           ],
                         ),
                       ),
                     ],
                   ),
                   Column(
                     children: [
                       _progress == null
                           ? SizedBox.shrink()
                           : Text(
                               '$_progress%',
                               style: TextStyle(
                                   color: MyColors.white, fontSize: 12),
                             ),
                       InkWell(
                         onTap: () {
                           if (_progress == null) {
                             VersionUpdate.downloadNewVersion(
                                 Url: _netVersionInfo?.url);
                             //'https://itunes.apple.com/cn/app/id414478124'
                           }
                         },
                         child: Container(
                           margin: EdgeInsets.only(
                               left: 20, right: 20, top: 5, bottom: 15),
                           decoration: BoxDecoration(
                             color: MyColors.white,
                             borderRadius:
                                 BorderRadius.all(Radius.circular(50)),
                           ),
                           child: Row(
                             mainAxisAlignment: MainAxisAlignment.center,
                             children: [
                               Container(
                                 padding: EdgeInsets.symmetric(vertical: 10),
                                 child: Text(
                                   '立刻升级',
                                   style: TextStyle(
                                       color: MyColors.yellow_17,
                                       fontSize: 17,
                                       fontWeight: FontWeight.bold),
                                 ),
                               )
                             ],
                           ),
                         ),
                       )
                     ],
                   )
                 ],
               ),
               SizedBox(
                 height: 14,
               ),
               _netVersionInfo?.forceFlag == '1'
                   ? SizedBox.shrink()
                   : InkWell(
                       onTap: () {
                         widget?.overlayEntry?.remove();
                       },
                       child: Icon(
                         Icons.cancel_outlined,
                         color: MyColors.white,
                         size: 30,
                       ),
                     )
             ],
           ),
         )),
   );
 }
}
使用:我是在闪屏页的初始化中调用的,按照自己的需求改就行
   //版本更新
   VersionUpdate.isUpdating();

说明:SpUtil.putString是个工具,就是存储本地版本号而已,改SharedPreferences去存就行。
Application.globalKey.currentState.overlay:

class Application {
  /// 全局key
  static final GlobalKey<NavigatorState> globalKey =
      GlobalKey<NavigatorState>();

注:适合刚入门看。缺少什么或者不懂的可以留言我补。刚接触flutter不久,各位指导指导。

上一篇下一篇

猜你喜欢

热点阅读