Flutter应用更新插件flutter_xupdate3的使用

Flutter应用更新插件flutter_xupdate3的使用

flutter_xupdate




flutter_xupdate 是一个基于 XUpdate 的 Flutter 插件,用于实现 Android 应用的更新功能。更多详细信息可查看 中文文档


关于我

微信公众号 掘金 知乎 CSDN 简书 SegmentFault B站 头条
我的Android开源之旅 点击我 点击我 点击我 点击我 点击我 点击我 点击我

视频教程

如何使用 flutter_xupdate

Stargazers over time

Stargazers over time


Getting Started

首先,在您的 Flutter 项目中集成 flutter_xupdate 插件:

pub 集成

dependencies:
  flutter_xupdate: ^2.0.3

github 集成

dependencies:
  flutter_xupdate:
    git:
      url: git://github.com/xuexiangjys/flutter_xupdate.git
      ref: master

UseCase

初始化

void initXUpdate() {
  if (Platform.isAndroid) {
    FlutterXUpdate.init(
      /// 是否输出日志
      debug: true,
      /// 是否使用post请求
      isPost: false,
      /// post请求是否是上传json
      isPostJson: false,
      /// 请求响应超时时间
      timeout: 25000,
      /// 是否开启自动模式
      isWifiOnly: false,
      /// 是否开启自动模式
      isAutoMode: false,
      /// 需要设置的公共参数
      supportSilentInstall: false,
      /// 在下载过程中,如果点击了取消的话,是否弹出切换下载方式的重试提示弹窗
      enableRetry: false,
    ).then((value) {
      updateMessage("初始化成功: $value");
    }).catchError((error) {
      print(error);
    });

    FlutterXUpdate.setUpdateHandler(
      onUpdateError: (Map<String, dynamic> message) async {
        print(message);
        setState(() {
          _message = "$message";
        });
      },
      onUpdateParse: (String json) async {
        return customParseJson(json);
      },
    );
  } else {
    updateMessage("iOS 暂不支持 XUpdate 更新");
  }
}

/// 自定义 JSON 解析
UpdateEntity customParseJson(String json) {
  AppInfo appInfo = AppInfo.fromJson(json);
  return UpdateEntity(
    hasUpdate: appInfo.hasUpdate,
    isIgnorable: appInfo.isIgnorable,
    versionCode: appInfo.versionCode,
    versionName: appInfo.versionName,
    updateContent: appInfo.updateLog,
    downloadUrl: appInfo.apkUrl,
    apkSize: appInfo.apkSize,
  );
}

JSON 格式

{
  "Code": 0, // 0 代表请求成功,非0 代表失败
  "Msg": "", // 请求出错的信息
  "UpdateStatus": 1, // 0 代表不更新,1 代表有版本更新,不需要强制升级,2 代表有版本更新,需要强制升级
  "VersionCode": 3,
  "VersionName": "1.0.2",
  "ModifyContent": "1、优化 api 接口。\n2、添加使用 demo 演示。\n3、新增自定义更新服务 API 接口。\n4、优化更新提示界面。",
  "DownloadUrl": "https://raw.githubusercontent.com/xuexiangjys/XUpdate/master/apk/xupdate_demo_1.0.2.apk",
  "ApkSize": 2048,
  "ApkMd5": "..."  // md5 值没有的话,就无法保证 apk 是否完整,每次都会重新下载。框架默认使用的是 md5 加密。
}

检查更新

/// 默认 App 更新
void checkUpdateDefault() {
  FlutterXUpdate.checkUpdate(url: _updateUrl);
}

/// 默认 App 更新 + 支持后台更新
void checkUpdateSupportBackground() {
  FlutterXUpdate.checkUpdate(url: _updateUrl, supportBackgroundUpdate: true);
}

/// 调整宽高比
void checkUpdateRatio() {
  FlutterXUpdate.checkUpdate(url: _updateUrl, widthRatio: 0.6);
}

/// 强制更新
void checkUpdateForce() {
  FlutterXUpdate.checkUpdate(url: _updateUrl2);
}

/// 自动模式, 如果需要完全无人干预,自动更新,需要 root 权限【静默安装需要】
void checkUpdateAutoMode() {
  FlutterXUpdate.checkUpdate(url: _updateUrl, isAutoMode: true);
}

/// 下载时点击取消允许切换下载方式
void enableChangeDownLoadType() {
  FlutterXUpdate.checkUpdate(
    url: _updateUrl,
    overrideGlobalRetryStrategy: true,
    enableRetry: true,
    retryContent: "Github 下载速度太慢了,是否考虑切换蒲公英下载?",
    retryUrl: "https://www.pgyer.com/flutter_learn",
  );
}

自定义 JSON 格式

  1. 设置自定义解析器
FlutterXUpdate.setCustomParseHandler(
  onUpdateParse: (String json) async {
    return customParseJson(json);
  },
);

/// 解析自定义 JSON 内容到 UpdateEntity 实体类
UpdateEntity customParseJson(String json) {
  AppInfo appInfo = AppInfo.fromJson(json);
  return UpdateEntity(
    hasUpdate: appInfo.hasUpdate,
    isIgnorable: appInfo.isIgnorable,
    versionCode: appInfo.versionCode,
    versionName: appInfo.versionName,
    updateContent: appInfo.updateLog,
    downloadUrl: appInfo.apkUrl,
    apkSize: appInfo.apkSize,
  );
}
  1. 设置参数 isCustomParsetrue
FlutterXUpdate.checkUpdate(url: _updateUrl3, isCustomParse: true);

直接传入 UpdateEntity 进行更新提示

void checkUpdate8() {
  FlutterXUpdate.updateByInfo(updateEntity: customParseJson(_customJson));
}

自定义更新提示样式

当前仅支持主题颜色和顶部图片定制!

  1. 配置顶部图片,路径:android/app/src/main/res/values/drawable,例如:bg_update_top.png

  2. 设置参数 themeColortopImageResbuttonTextColor

void customPromptDialog() {
  FlutterXUpdate.checkUpdate(
    url: _updateUrl,
    themeColor: '#FFFFAC5D',
    topImageRes: 'bg_update_top',
    buttonTextColor: '#FFFFFFFF',
  );
}

注意:当使用命令 flutter build apk 构建发布包时,若使用了 topImageRes 属性,则必须配置 shrinkResourcesfalse,否则弹窗会显示异常!


Property Value

初始化

名称 类型 默认值 描述
debug bool false 是否输出日志
isPost bool false 是否使用 POST 请求
isPostJson bool false POST 请求是否上传 JSON 格式数据
timeout int 20000ms 请求响应超时时间
isWifiOnly bool true 是否仅在 Wi-Fi 下更新
isAutoMode bool false 是否开启自动模式
supportSilentInstall bool false 是否支持静默安装(需要设备有 root 权限)
enableRetry bool false 下载过程中点击取消是否弹出重试弹窗
retryContent String ‘’ 重试弹窗提示内容
retryUrl String ‘’ 点击重试后跳转的 URL
params Map / 需要设置的公共参数

CheckUpdate

名称 类型 默认值 描述
url String / 版本检查的 URL
params Map / 参数
supportBackgroundUpdate bool false 是否支持后台更新
isAutoMode bool false 是否开启自动模式
isCustomParse bool false 是否为自定义解析协议
themeColor String ‘’ 弹窗主题颜色
topImageRes String ‘’ 弹窗顶部图片资源名称
buttonTextColor String ‘’ 按钮文字颜色
widthRatio double / 版本更新提示框宽度占屏幕比例
heightRatio double / 版本更新提示框高度占屏幕比例
overrideGlobalRetryStrategy bool false 是否覆盖全局重试策略
enableRetry bool false 下载过程中点击取消是否弹出重试弹窗
retryContent String ‘’ 重试弹窗提示内容
retryUrl String ‘’ 点击重试后跳转的 URL

完整示例 Demo

以下是一个完整的示例代码,展示如何使用 flutter_xupdate 插件实现应用更新功能:

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:flutter_xupdate_example/app_info.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _message = '';
  String _customJson = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    initXUpdate();
    loadJsonFromAsset();
  }

  Future<void> loadJsonFromAsset() async {
    _customJson = await rootBundle.loadString('assets/update_custom.json');
  }

  /// 初始化
  void initXUpdate() {
    if (Platform.isAndroid) {
      FlutterXUpdate.init(
        debug: true,
        isPost: false,
        isPostJson: false,
        timeout: 25000,
        isWifiOnly: false,
        isAutoMode: false,
        supportSilentInstall: false,
        enableRetry: false,
      ).then((value) {
        updateMessage('初始化成功: $value');
      }).catchError((error) {
        print(error);
      });

      FlutterXUpdate.setUpdateHandler(
        onUpdateError: (Map<String, dynamic> message) async {
          print(message);
          if (message["code"] == 4000) {
            FlutterXUpdate.showRetryUpdateTipDialog(
              retryContent: "Github 被墙无法继续下载,是否考虑切换蒲公英下载?",
              retryUrl: "https://www.pgyer.com/flutter_learn",
            );
          }
          setState(() {
            _message = "$message";
          });
        },
        onUpdateParse: (String json) async {
          return customParseJson(json);
        },
      );
    } else {
      updateMessage('iOS 暂不支持 XUpdate 更新');
    }
  }

  void updateMessage(String message) {
    setState(() {
      _message = message;
    });
  }

  /// 将自定义的 JSON 内容解析为 UpdateEntity 实体类
  UpdateEntity customParseJson(String json) {
    AppInfo appInfo = AppInfo.fromJson(json);
    return UpdateEntity(
      hasUpdate: appInfo.hasUpdate,
      isIgnorable: appInfo.isIgnorable,
      versionCode: appInfo.versionCode,
      versionName: appInfo.versionName,
      updateContent: appInfo.updateLog,
      downloadUrl: appInfo.apkUrl,
      apkSize: appInfo.apkSize,
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('flutter_xupdate Demo'),
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                alignment: Alignment.topLeft,
                height: 150,
                color: Colors.grey,
                padding: const EdgeInsets.all(10),
                child: Text(
                  _message,
                  style: const TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
              ButtonBar(
                alignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ElevatedButton(
                    child: const Text('默认 App 更新'),
                    onPressed: checkUpdateDefault,
                  ),
                  ElevatedButton(
                    child: const Text('默认 App 更新 + 支持后台更新'),
                    onPressed: checkUpdateSupportBackground,
                  ),
                ],
              ),
              ButtonBar(
                alignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ElevatedButton(
                    child: const Text('调整宽高比'),
                    onPressed: checkUpdateRatio,
                  ),
                  ElevatedButton(
                    child: const Text('强制更新'),
                    onPressed: checkUpdateForce,
                  ),
                  ElevatedButton(
                    child: const Text('自动模式'),
                    onPressed: checkUpdateAutoMode,
                  ),
                ],
              ),
              ButtonBar(
                alignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ElevatedButton(
                    child: const Text('下载时点击取消允许切换下载方式'),
                    onPressed: enableChangeDownLoadType,
                  ),
                  ElevatedButton(
                    child: const Text('显示重试提示弹窗'),
                    onPressed: showRetryDialogTip,
                  ),
                ],
              ),
              ButtonBar(
                alignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ElevatedButton(
                    child: const Text('使用自定义 JSON 解析'),
                    onPressed: customJsonParse,
                  ),
                  ElevatedButton(
                    child: const Text('直接传入 UpdateEntity 进行更新'),
                    onPressed: checkUpdateByUpdateEntity,
                  ),
                ],
              ),
              ButtonBar(
                alignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ElevatedButton(
                    child: const Text('自定义更新弹窗样式'),
                    onPressed: customPromptDialog,
                  ),
                  ElevatedButton(
                    child: const Text('定时更新'),
                    onPressed: timerUpdateTask,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  void checkUpdateDefault() {
    FlutterXUpdate.checkUpdate(url: _updateUrl);
  }

  void checkUpdateSupportBackground() {
    FlutterXUpdate.checkUpdate(url: _updateUrl, supportBackgroundUpdate: true);
  }

  void checkUpdateRatio() {
    FlutterXUpdate.checkUpdate(url: _updateUrl, widthRatio: 0.6);
  }

  void checkUpdateForce() {
    FlutterXUpdate.checkUpdate(url: _updateUrl2);
  }

  void checkUpdateAutoMode() {
    FlutterXUpdate.checkUpdate(url: _updateUrl, isAutoMode: true);
  }

  void enableChangeDownLoadType() {
    FlutterXUpdate.checkUpdate(
      url: _updateUrl,
      overrideGlobalRetryStrategy: true,
      enableRetry: true,
      retryContent: "Github 下载速度太慢了,是否考虑切换蒲公英下载?",
      retryUrl: "https://www.pgyer.com/flutter_learn",
    );
  }

  void showRetryDialogTip() {
    FlutterXUpdate.showRetryUpdateTipDialog(
      retryContent: "Github 下载速度太慢了,是否考虑切换蒲公英下载?",
      retryUrl: "https://www.pgyer.com/flutter_learn",
    );
  }

  void customJsonParse() {
    FlutterXUpdate.checkUpdate(url: _updateUrl3, isCustomParse: true);
  }

  void checkUpdateByUpdateEntity() {
    FlutterXUpdate.updateByInfo(updateEntity: customParseJson(_customJson));
  }

  void customPromptDialog() {
    FlutterXUpdate.checkUpdate(
      url: _updateUrl,
      themeColor: '#FFFFAC5D',
      topImageRes: 'bg_update_top',
      buttonTextColor: '#FFFFFFFF',
    );
  }

  void timerUpdateTask() {
    Timer.periodic(const Duration(seconds: 5), (timer) {
      checkUpdateDefault();
    });
  }
}

更多关于Flutter应用更新插件flutter_xupdate3的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用更新插件flutter_xupdate3的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_xupdate3 是一个用于 Flutter 应用的插件,主要用于实现应用内更新功能。它基于 XUpdate 库,支持 Android 和 iOS 平台,可以帮助开发者轻松实现应用版本检查、下载和安装等功能。

以下是 flutter_xupdate3 的基本使用步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 flutter_xupdate3 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_xupdate3: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 初始化插件

在应用的 main.dart 文件中初始化 flutter_xupdate3 插件:

import 'package:flutter/material.dart';
import 'package:flutter_xupdate3/flutter_xupdate3.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 XUpdate
  await FlutterXupdate3.init(
    debug: true,  // 是否开启调试模式
    isWifiOnly: false,  // 是否仅在 Wi-Fi 下进行更新
    isAutoMode: false,  // 是否自动模式
    supportSilentInstall: false,  // 是否支持静默安装
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter XUpdate3 Demo',
      home: HomePage(),
    );
  }
}

3. 检查更新

在需要检查更新的地方调用 checkUpdate 方法:

import 'package:flutter/material.dart';
import 'package:flutter_xupdate3/flutter_xupdate3.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter XUpdate3 Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 检查更新
            await FlutterXupdate3.checkUpdate(
              url: 'https://your-update-api.com/check-update',  // 更新检查的 API 地址
              params: {},  // 请求参数
              onUpdate: (Map<String, dynamic> updateInfo) {
                // 更新信息回调
                print('Update Info: $updateInfo');
              },
              onError: (String error) {
                // 错误回调
                print('Error: $error');
              },
            );
          },
          child: Text('Check for Update'),
        ),
      ),
    );
  }
}

4. 处理更新信息

onUpdate 回调中,你可以根据返回的更新信息来决定是否提示用户更新。通常,更新信息会包含新版本号、更新内容、下载地址等。

onUpdate: (Map<String, dynamic> updateInfo) {
  // 解析更新信息
  String newVersion = updateInfo['version'];
  String updateContent = updateInfo['content'];
  String downloadUrl = updateInfo['url'];

  // 提示用户更新
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('New Version Available'),
        content: Text('Version: $newVersion\n\n$updateContent'),
        actions: <Widget>[
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              // 开始下载更新
              FlutterXupdate3.startDownload(
                url: downloadUrl,
                onProgress: (int progress) {
                  // 下载进度回调
                  print('Download Progress: $progress%');
                },
                onSuccess: (String path) {
                  // 下载成功回调
                  print('Download Success: $path');
                },
                onError: (String error) {
                  // 下载错误回调
                  print('Download Error: $error');
                },
              );
            },
            child: Text('Update'),
          ),
        ],
      );
    },
  );
},
回到顶部