Flutter应用版本更新插件playx_version_update的使用

Flutter应用版本更新插件playx_version_update的使用

Playx Version Update

Playx Version Update 插件让您能够轻松管理应用程序更新,为用户提供无缝体验。您可以轻松通知用户有关新更新的信息,提供灵活或立即更新选项,并自定义更新过程。

功能

  • 更新对话框:通过 Android 的 Material Design 对话框和 iOS 的 Cupertino 对话框告知用户新版本的应用。
  • Google Play 集成:直接从您的应用程序中启动灵活或立即更新。
  • 可定制的 UI:显示包含发行说明和最低版本要求的自定义更新界面。
  • 应用内更新页面:在应用程序内部展示更新信息和选项,以实现无缝用户体验。

安装

pubspec.yaml 文件中的 dependencies 下添加以下内容:

dependencies:
  playx_version_update: ^0.1.0

要求

  • 目前仅支持 Android 和 iOS 平台。
  • Flutter >=3.19.0
  • Dart >=3.3.0 <4.0.0
  • Android compileSDK 34
  • 最低 Android SDK 版本为 23
  • Java 17
  • Android Gradle Plugin >=8.3.0
  • Gradle wrapper >=8.4

使用方法

显示更新对话框

以下是用于显示更新对话框的代码示例:

final result = await PlayxVersionUpdate.showUpdateDialog(
  context: context,
  showReleaseNotes: false,
  googlePlayId: 'other app id',
  minVersion: '1.0.0',
  title: (info) => 'A new update is available',
  forceUpdate: true,
  showPageOnForceUpdate: true,
  isDismissible: false,
  onCancel: (info) {
    final forceUpdate = info.forceUpdate;
    if (forceUpdate) {
      exit(0);
    }
  },
);

result.when(success: (isShowed) {
  print('showUpdateDialog success :');
}, error: (error) {
  print('showUpdateDialog error : ${error.message}');
});

应用内更新

对于 Android 和 iOS,可以使用以下代码来显示应用内更新对话框:

final result = await PlayxVersionUpdate.showInAppUpdateDialog(
  context: context,
  type: PlayxAppUpdateType.flexible,
  appStoreId: 'app bundle id',
  showReleaseNotes: true,
  releaseNotesTitle: (info) => 'Recent Updates of ${info.newVersion}',
  onIosUpdate: (info, launchMode) async {
    final storeUrl = info.storeUrl;
    final res = await PlayxVersionUpdate.openStore(storeUrl: storeUrl);
    res.when(success: (success) {
      print('playx_open_store: success :$success');
    }, error: (error) {
      print('playx_open_store: error :$error');
    });
  },
);

result.when(success: (isShowed) {
  print('showInAppUpdateDialog success : $isShowed');
}, error: (error) {
  print('showInAppUpdateDialog error : $error ${error.message}');
});

检查版本并创建自定义UI

您可以通过 PlayxVersionUpdate.checkVersion 方法检查 Google Play 或 App Store 中的应用版本,并根据需要创建自定义 UI。例如,我们可以显示 PlayxUpdatePage 来展示应用更新信息:

final result = await PlayxVersionUpdate.checkVersion(
  localVersion: '1.0.0',
  newVersion: '1.1.0',
  forceUpdate: true,
  googlePlayId: 'your app package name',
  appStoreId: 'your app bundle id',
  country: 'us',
  language: 'en',
);

result.when(success: (info) {
  Navigator.push(
    context,
    MaterialPageRoute<void>(
      builder: (BuildContext context) => PlayxUpdatePage(
        versionUpdateInfo: info,
        showReleaseNotes: false,
        showDismissButtonOnForceUpdate: false,
        leading: Image.network('image url'),
        title: (info) => "It's time to update",
        description: (info) =>
            'A new version of the app is now available.\nThe app needs to be updated to the latest version in order to work properly.\nEnjoy the latest version features now.',
      ),
    ),
  );
}, error: (error) {
  // handle the error that happened here.
});

最小应用版本

您可以在 Google Play 或 App Store 的描述末尾添加 [Minimum Version :1.0.0] 来设置最小版本。这将强制用户更新到指定版本。

Google Play 应用内更新

立即更新

立即更新会占用整个屏幕,用户必须更新并重启应用才能继续使用。适用于对应用核心功能至关重要的更新。

final result = await PlayxVersionUpdate.startImmediateUpdate();
result.when(success: (isSucceeded) {
  // 用户接受并成功更新
}, error: (error) {
  print('an error occurred :${error.message}');
});

灵活更新

灵活更新允许用户在后台下载更新时继续与应用交互。

final result = await PlayxVersionUpdate.startFlexibleUpdate();
result.when(success: (isStarted) {
  // 用户接受了更新
}, error: (error) {
  print('an error occurred :${error.message}');
});

监听灵活更新状态

您可以监听 listenToFlexibleDownloadUpdate 流来监控更新进度。

void listenToFlexibleDownloadUpdates() {
  downloadInfoStreamSubscription =
      PlayxVersionUpdate.listenToFlexibleDownloadUpdate().listen((info) {
    if (info == null) return;
    if (info.status == PlayxDownloadStatus.downloaded) {
      completeFlexibleUpdate();
    } else if (info.status == PlayxDownloadStatus.downloading) {
      print('current download in progress : bytes downloaded:${info.bytesDownloaded} total bytes to download : ${info.totalBytesToDownload}');
    }
  });
}

完成灵活更新

当检测到 PlayxDownloadStatus.downloaded 状态时,需要重启应用以安装更新。

Future<void> completeFlexibleUpdate() async {
  final snackBar = SnackBar(
    content: const Text('An update has just been downloaded.'),
    action: SnackBarAction(
        label: 'Restart',
        onPressed: () async {
          final result = await PlayxVersionUpdate.completeFlexibleUpdate();
          result.when(success: (isCompleted) {
            print('completeFlexibleUpdate isCompleted : $isCompleted');
          }, error: (error) {
            print('completeFlexibleUpdate error has happened: ${error.message}');
          });
        }),
    duration: const Duration(seconds: 10),
  );
  globalKey.currentState?.showSnackBar(snackBar);
}

重要提示

应用内更新仅在应用从 Google Play 下载时有效。要测试应用内更新,可以使用 Google Play 内部应用共享内部测试

文档和参考

示例代码

完整的示例代码可以在 GitHub 上找到。


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

1 回复

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


当然,以下是如何在Flutter应用中使用playx_version_update插件来实现版本更新的示例代码。这个插件主要用于检查Google Play商店中的最新版本,并提示用户更新应用。

首先,确保你已经在pubspec.yaml文件中添加了playx_version_update依赖:

dependencies:
  flutter:
    sdk: flutter
  playx_version_update: ^最新版本号  # 请替换为最新的版本号

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

接下来,在你的Flutter应用中配置和使用这个插件。以下是一个简单的示例:

  1. 导入插件

在你的Dart文件中导入插件:

import 'package:playx_version_update/playx_version_update.dart';
  1. 初始化插件并检查更新

通常,你会在应用启动时检查更新。你可以在main.dart中的MyApp类的构造函数或initState方法中进行这个操作。

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _checkForUpdates();
  }

  Future<void> _checkForUpdates() async {
    try {
      // 替换为你的应用的包名
      final String packageName = 'com.example.yourapp';
      
      // 创建一个PlayxVersionUpdate实例
      final PlayxVersionUpdate playxVersionUpdate = PlayxVersionUpdate(
        context: context,
        packageName: packageName,
        // 可选参数,设置检查更新的间隔时间(以天为单位)
        // checkInterval: 1,
        // 可选参数,设置版本更新对话框的标题和消息
        dialogTitle: '新版本更新',
        dialogMessage: '发现新版本,请更新以获得最佳体验。',
        // 可选参数,设置版本更新对话框的按钮文本
        dialogPositiveButtonText: '立即更新',
        dialogNegativeButtonText: '稍后更新',
        // 可选参数,设置版本更新对话框的按钮点击回调
        dialogPositiveButtonOnPressed: () async {
          // 打开Google Play商店的应用页面
          await PlayxVersionUpdate.openPlayStore(packageName: packageName);
        },
        dialogNegativeButtonOnPressed: () {
          // 用户选择稍后更新,这里可以添加一些逻辑,比如记录用户的选择
        },
      );

      // 检查版本更新
      final bool isUpdateAvailable = await playxVersionUpdate.checkVersion();
      if (isUpdateAvailable) {
        // 显示版本更新对话框
        playxVersionUpdate.showDialog();
      }
    } catch (e) {
      // 处理异常,例如网络错误
      print('检查版本更新时发生错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('版本更新示例'),
        ),
        body: Center(
          child: Text('检查应用版本更新...'),
        ),
      ),
    );
  }
}

在这个示例中,我们首先导入了playx_version_update插件,然后在MyApp类的initState方法中调用_checkForUpdates函数来检查版本更新。如果检测到有新版本可用,则会显示一个对话框提示用户更新应用。

请注意,你需要将packageName替换为你的实际应用的包名。

此外,PlayxVersionUpdate类提供了多个可选参数来自定义版本更新对话框的外观和行为,你可以根据需要调整这些参数。

希望这个示例代码能帮助你在Flutter应用中实现版本更新功能!

回到顶部