Flutter应用升级管理插件flutter_upgrader的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter应用升级管理插件flutter_upgrader的使用

安装

pubspec.yaml 中添加依赖项:

dependencies:
  flutter_upgrader: ^1.1.20

然后在命令行运行以下命令:

flutter pub get

使用示例

Android 示例
  1. AndroidManifest.xml 中添加 provider
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  package="com.example.app">
  <application>
    ...
    <provider
      android:name="androidx.core.content.FileProvider"
      android:authorities="${applicationId}.fileprovider"
      android:grantUriPermissions="true"
      android:exported="false">
      <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
    </provider>
  </application>
</manifest>
  1. 新增 res/xml/file_paths.xml 文件:
<paths>
  <external-path
    name="external-path"
    path="."
  />

  <external-cache-path
    name="external-cache-path"
    path="."
  />

  <external-files-path
    name="external-files-path"
    path="."
  />

  <files-path
    name="files_path"
    path="."
  />

  <cache-path
    name="cache-path"
    path="."
  />

  <root-path
    name="name"
    path="."
  />
</paths>
  1. 点击升级前往应用商店:
import 'package:flutter/material.dart';
import 'package:flutter_upgrader/flutter_upgrader.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Upgrader Plugin'),
      ),
      body: DividerTheme(
        data: const DividerThemeData(color: Colors.white), // support
        child: Container(
          margin: const EdgeInsets.only(top: 50),
          alignment: Alignment.topCenter,
          child: const UpgradeButton(),
        ),
      ),
    );
  }
}

class UpgradeButton extends StatelessWidget {
  const UpgradeButton({super.key});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButtonTheme.of(context).style,
      child: Container(
        width: 270,
        height: 44,
        alignment: Alignment.topCenter,
        padding: const EdgeInsets.all(11.0),
        child: const Text(
          '升 级',
          style: TextStyle(fontSize: 18),
        ),
      ),
      onPressed: () async {
        final Future<AppUpgradeInfo> appUpgradeInfo = Future.value(
          AppUpgradeInfo(
            title: '更新提示',
            version: '1.0.0',
            contents: ['有新版本哟,请更新~'],
            force: true,
          ),
        );

        if (Platform.isAndroid) {
          await AppUpgradeManager.upgrade(
            context,
            appUpgradeInfo,
            appMarketInfo: AppMarketManager.huaWei,
            // dividerTheme: const DividerThemeData(color: Colors.white), // support
          );
        }

        if (Platform.isIOS) {
          await AppUpgradeManager.upgrade(
            context,
            iosAppId: '',
            appUpgradeInfo,
            // dividerTheme: const DividerThemeData(color: Colors.white), // support
          );
        }
      },
    );
  }
}

从指定的 URL 下载 APK:

final Future<AppUpgradeInfo> appUpgradeInfo = Future.value(
  AppUpgradeInfo(
    title: '更新提示',
    version: '1.0.0',
    contents: ['有新版本哟,请更新~'],
    force: true,
  ),
);

await AppUpgradeManager.upgrade(
  context,
  appUpgradeInfo,
  apkDownloadUrl: 'http://xxx.xxx.com/upgrade.apk',
  onCancel: () {},
  onOk: () {},
);

iOS 示例
  1. 点击升级前往应用商店:
final Future<AppUpgradeInfo> appUpgradeInfo = Future.value(
  AppUpgradeInfo(
    title: '更新提示',
    version: ' 1.0.0',
    contents: ['有新版本哟,请更新~'],
    force: true,
  ),
);

await AppUpgradeManager.upgrade(
  context,
  appUpgradeInfo,
  iosAppId: 'xxxxxxxx', // iOS appId
  onCancel: () {},
  onOk: () {},
);

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_upgrader插件来实现应用升级管理的示例代码。flutter_upgrader是一个用于检查应用版本并在新版本可用时提示用户更新的插件。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加flutter_upgrader的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_upgrader: ^x.y.z  # 替换为最新版本号

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

2. 配置AndroidManifest.xmlInfo.plist

确保你的应用有网络访问权限。对于Android,在AndroidManifest.xml中添加以下权限:

<uses-permission android:name="android.permission.INTERNET"/>

对于iOS,在Info.plist中添加NSAppTransportSecurity配置以允许HTTP请求(如果适用):

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

3. 初始化flutter_upgrader

在你的主应用文件(通常是main.dart)中,配置并初始化flutter_upgrader

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 初始化flutter_upgrader
    _initFlutterUpgrader();

    return MaterialApp(
      title: 'Flutter App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }

  void _initFlutterUpgrader() {
    FlutterUpgrader(
      context,
      androidAppId: "com.example.yourapp",  // 替换为你的Android应用ID
      iOSAppId: "123456789",  // 替换为你的iOS应用ID
      // 指定新版本信息的API端点
      newVersionAPI: "https://yourserver.com/api/version",
      // 强制更新标志(可选)
      mandatoryUpdate: false,
      // 更新对话框样式(可选)
      upgrader: (context) => MaterialUpgrader(
        title: Text("新版本可用"),
        description: Text(
          "发现新版本,点击更新以获取最新功能。",
          style: TextStyle(fontSize: 16),
        ),
        skipButton: Text("稍后更新"),
        downloadButton: Text("立即更新"),
        // 下载进度条样式(可选)
        progressWidget: (progress) => Center(
          child: CircularProgressIndicator(
            value: progress,
          ),
        ),
      ),
      // 下载完成后回调(可选)
      onDownloadProgress: (progress) {
        print("下载进度: $progress");
      },
      // 更新完成后回调(可选)
      onComplete: () {
        print("更新完成");
        // 这里可以添加重启应用的逻辑
      },
      // 检查更新频率(可选)
      daysBetweenCheck: 1,
    )..checkVersion();
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Text('Hello, Flutter!'),
      ),
    );
  }
}

4. 设置版本信息API

你需要在服务器端设置一个API端点来返回当前应用的版本信息。API响应的JSON格式示例如下:

{
  "latest_version": "2.0.0",
  "release_notes": "这是2.0.0版本的更新说明。",
  "mandatory_update": false,
  "url": "https://yourserver.com/path/to/your/apk/or/ipa"
}

5. 运行应用

现在,你可以运行你的Flutter应用。当新版本可用时,flutter_upgrader将显示一个对话框提示用户更新。

请注意,这只是一个基本的示例,你可能需要根据你的具体需求进一步定制和扩展代码。

回到顶部