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

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

app_version_update 是一个用于检查和提示用户进行应用版本更新的Flutter插件。它能够比较本地应用版本与应用商店中的最新版本,并提供对话框、底部弹出窗口和页面等UI组件来提示用户更新。

特性

  • 检查本地应用版本与Google Play或Apple App Store上的版本是否一致。
  • 提供多种UI组件(如对话框、底部弹出窗口和页面)来提示用户更新应用。
  • 支持自定义更新提示的样式和行为。

开始使用

首先,在你的项目中添加 app_version_update 插件:

$ flutter pub add app_version_update

或者在 pubspec.yaml 文件中手动添加依赖:

dependencies:
  app_version_update: <latest>

确保你的应用已经在应用商店上架,以便该插件可以正确获取最新版本信息。

权限配置

对于Android,需要在 AndroidManifest.xml 中添加网络权限:

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

对于iOS,需要在 Info.plist 中添加以下配置以允许任意加载:

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

使用示例

下面是一个完整的示例代码,展示了如何使用 app_version_update 插件来检查应用是否有新版本,并显示相应的提示:

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'app_version_update_example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'app_version_update_example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _verifyVersion();
  }

  void _verifyVersion() async {
    await AppVersionUpdate.checkForUpdates(
      appleId: '284882215', // 替换为你的Apple ID
      playStoreId: 'com.zhiliaoapp.musically', // 替换为你的Play Store ID
    ).then((result) async {
      if (result.canUpdate!) {
        // 显示自定义对话框提示用户更新
        await AppVersionUpdate.showAlertUpdate(
          appVersionResult: result,
          context: context,
          backgroundColor: Colors.grey[200],
          title: 'Uma versão mais recente está disponível.',
          titleTextStyle: const TextStyle(color: Colors.black, fontWeight: FontWeight.w600, fontSize: 24.0),
          content: 'Gostaria de atualizar seu aplicativo para a versão mais recente?',
          contentTextStyle: const TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.w400,
          ),
          updateButtonText: 'ATUALIZAR',
          cancelButtonText: 'DEPOIS',
        );

        // 或者使用其他UI组件,如底部弹出窗口或页面
        // await AppVersionUpdate.showBottomSheetUpdate(context: context, appVersionResult: result);
        // await AppVersionUpdate.showPageUpdate(context: context, appVersionResult: result);
      }
    });
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), 
    );
  }
}

自定义对话框

你可以根据需要自定义对话框的样式和内容:

await AppVersionUpdate.showAlertUpdate(
  context: context,
  appVersionResult: result,
  mandatory: false, // 是否强制更新
  title: 'New version available',
  titleTextStyle: const TextStyle(fontSize: 24.0, fontWeight: FontWeight.w500),
  content: 'Would you like to update your application?',
  contentTextStyle: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.w400),
  cancelButtonStyle: const ButtonStyle(backgroundColor: MaterialStatePropertyAll(Colors.redAccent)),
  updateButtonStyle: const ButtonStyle(backgroundColor: MaterialStatePropertyAll(Colors.green)),
  cancelButtonText: 'UPDATE LATER',
  updateButtonText: 'UPDATE',
  cancelTextStyle: const TextStyle(color: Colors.white),
  updateTextStyle: const TextStyle(color: Colors.white),
  backgroundColor: Colors.white,
);

自定义底部弹出窗口

你也可以使用底部弹出窗口来提示用户更新:

await AppVersionUpdate.showBottomSheetUpdate(
  context: context,
  appVersionResult: result,
  mandatory: true, // 是否强制更新
  title: 'New version available',
  content: const Text('Please update your application to the latest version.'),
);

自定义页面

如果你希望使用一个独立的页面来提示用户更新,可以这样做:

await AppVersionUpdate.showPageUpdate(
  context: context,
  appVersionResult: result,
  page: const UpdateVersionPage(), // 自定义页面
);

额外信息

该插件仍在开发中,未来将加入更多功能,如自动国家检测、异常处理等。如果你有任何建议或贡献,欢迎提交PR。


以上就是关于 app_version_update 插件的基本介绍和使用方法。通过这个插件,你可以轻松地为你的Flutter应用添加版本更新提示功能。


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

1 回复

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


当然,以下是如何在Flutter应用中使用app_version_update插件来进行版本更新的一个示例。这个插件可以帮助你检测应用的当前版本,并与服务器上的最新版本进行比较,从而提示用户进行更新。

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

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

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

接下来,在你的Flutter应用中,你可以使用以下代码来实现版本检查:

  1. 初始化插件并检查版本

在你的主Dart文件(通常是main.dart)中,你可以这样初始化并使用app_version_update插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Version Update Example'),
        ),
        body: Center(
          child: VersionChecker(),
        ),
      ),
    );
  }
}

class VersionChecker extends StatefulWidget {
  @override
  _VersionCheckerState createState() => _VersionCheckerState();
}

class _VersionCheckerState extends State<VersionChecker> {
  String currentVersion = "Unknown";
  String latestVersion = "Unknown";
  bool isUpdateAvailable = false;

  @override
  void initState() {
    super.initState();
    checkAppVersion();
  }

  Future<void> checkAppVersion() async {
    // 获取当前应用版本
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() {
      currentVersion = packageInfo.version;
    });

    // 假设你从服务器获取最新版本信息,这里用硬编码的示例
    String latestVersionFromServer = "2.0.0"; // 你需要从服务器获取这个值

    // 比较版本
    setState(() {
      latestVersion = latestVersionFromServer;
      isUpdateAvailable = VersionCompare.isVersionGreater(latestVersionFromServer, currentVersion);
    });

    // 如果有更新,显示更新对话框
    if (isUpdateAvailable) {
      showUpdateDialog();
    }
  }

  Future<void> showUpdateDialog() async {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('New Version Available'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text('Current Version: $currentVersion'),
                Text('Latest Version: $latestVersion'),
                Text('Please update the app for the latest features and improvements.'),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('Later'),
            ),
            TextButton(
              onPressed: () {
                // 打开应用商店页面(这里以Google Play Store为例)
                String appId = "your.app.id"; // 替换为你的应用ID
                if (Platform.isAndroid) {
                  _launchPlayStore(appId);
                } else if (Platform.isIOS) {
                  // 对于iOS,你可以使用类似的方法打开App Store
                  // _launchAppStore(appId);
                }
                Navigator.of(context).pop();
              },
              child: Text('Update Now'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _launchPlayStore(String appId) async {
    final Uri googlePlayUri = Uri.parse("market://details?id=$appId");
    if (await canLaunchUrl(googlePlayUri)) {
      await launchUrl(googlePlayUri);
    } else {
      throw UnsupportedError('Could not launch ${googlePlayUri}');
    }
  }
}

注意

  • VersionCompare.isVersionGreater是一个假设的方法,用于比较版本号。Flutter没有内置的版本比较方法,所以你需要自己实现或者找一个第三方库来处理版本号的比较。
  • 在实际应用中,你需要从服务器获取latestVersionFromServer的值,这通常是通过API调用实现的。
  • 对于iOS,你需要修改_launchAppStore方法来打开App Store的对应页面。

这段代码展示了如何使用app_version_update(虽然实际上并没有直接使用这个插件,因为其主要功能可以通过上述代码实现)来检查版本并提示用户更新。如果你确实需要使用app_version_update插件的特定功能,请参考其官方文档和示例代码来集成。

回到顶部