Flutter应用更新提示插件update_available的使用

Flutter应用更新提示插件update_available的使用

插件简介

update_available 是一个用于检查Flutter应用程序是否有可用更新的插件。它支持Android和iOS平台,并基于发布到各自应用商店的应用版本进行版本检查。该插件提供了简单易用的功能,使得开发者可以轻松集成应用更新提醒功能。

特性

  • 为您的Android或iOS应用提供简单的单个函数来获取更新可用性。
  • 基于已发布的应用版本进行版本检查。

使用方法

添加依赖

在项目的pubspec.yaml文件中添加update_available作为依赖项:

dependencies:
  update_available: ^3.0.0

然后执行flutter pub get以更新包。

函数调用

update_available 提供了一个名为 getUpdateAvailability 的异步函数,它返回一个 Future<Availability> 类型的结果。Availability 是一个密封类(sealed class),有三种可能的状态:

  • UnknownAvailability:当无法确定是否可以升级时,可能是由于错误导致。
  • NoUpdateAvailable:当前安装的应用已经是最新版本。
  • UpdateAvailable:有新版本可用,建议用户更新应用。

可以通过 switch 语句来处理这三种状态:

void printAvailability() async {
  final updateAvailability = await getUpdateAvailability();

  final text = switch (availability) {
    UpdateAvailable() => "There's an update to you app! Please, update it "
                         "so you have access to the latest features!",
    NoUpdateAvailable() => 'No update is available for your app.',
    UnknownAvailability() => "It was not possible to determine if there is or not "
                             "an update for your app.",
  };

  print(text);
}

此外,还可以通过设置命名参数 iosAppStoreRegion 来指定iOS版本检查所在的区域(ISO 3166-1 alpha-2格式)。

示例代码

下面是一个完整的示例项目,展示了如何使用 update_available 插件创建一个简单的界面,允许用户点击按钮检查是否有可用的更新。

import 'package:flutter/widgets.dart';
import 'package:update_available/update_available.dart';

// 引入自定义的颜色和按钮组件
import 'shared/button.dart';
import 'shared/colors.dart';

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

class UpdateAvailableExample extends StatefulWidget {
  const UpdateAvailableExample({Key? key}) : super(key: key);

  @override
  State<UpdateAvailableExample> createState() => _UpdateAvailableExampleState();
}

class _UpdateAvailableExampleState extends State<UpdateAvailableExample> {
  String text = 'Is there any update?';

  @override
  Widget build(BuildContext context) {
    return WidgetsApp(
      color: green,
      pageRouteBuilder: <T>(RouteSettings settings, WidgetBuilder builder) {
        return PageRouteBuilder(
          pageBuilder: (context, animation, secondaryAnimation) => builder(context),
        );
      },
      home: Container(
        padding: const EdgeInsets.all(24.0),
        color: green,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              text,
              textAlign: TextAlign.center,
              style: const TextStyle(
                color: red,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16.0),
            Button(
              onTap: _onTap,
              child: const Padding(
                padding: EdgeInsets.all(8.0),
                child: Text(
                  'Check for update!',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _onTap() async {
    setState(() {
      text = 'Checking...';
    });

    final availability = await getUpdateAvailability();

    setState(() {
      text = switch (availability) {
        UpdateAvailable() => "There's an update available!",
        NoUpdateAvailable() => "There's no update available!",
        UnknownAvailability() => "Sorry, couldn't determine if there is or not an available update!",
      };
    });
  }
}

此代码创建了一个简单的Flutter应用,包含一个文本框和一个按钮。当用户点击按钮时,它会调用 getUpdateAvailability() 函数来检查是否有新的应用版本,并根据结果更新界面上显示的消息。

Android测试说明

由于Android实现使用了Google Play的In App Update API,因此在本地调试时无法直接测试更新提示功能。为了能够在实际环境中测试,请按照以下步骤操作:

  1. 设置内部应用共享(Internal App Sharing)。
  2. 启用由Google Play签名的应用程序。
  3. 构建Android应用程序包(APK或AAB)。
  4. 将构建好的文件上传至内部应用共享页面。
  5. 安装第一个版本的应用。
  6. 提升版本号并重新构建、上传新版本。
  7. 在设备上打开新链接,但不要点击更新按钮。
  8. 打开应用,此时应该能看到应用内更新提示。

以上步骤参考自StackOverflow上的回答,具体细节可参阅相关文档。

希望这些信息对您有所帮助!如果您有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,以下是一个关于如何在Flutter应用中使用update_available插件来实现应用更新提示的示例代码。这个插件可以帮助你检测新版本并在应用内显示更新提示。

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

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

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

接下来,你可以在你的Flutter应用中按照以下步骤实现更新提示功能:

  1. 初始化插件并检查更新

在你的主文件(例如main.dart)中,初始化UpdateAvailable插件并检查是否有新版本可用。

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

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

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

class _MyAppState extends State<MyApp> {
  final UpdateAvailable _updateAvailable = UpdateAvailable();

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

  Future<void> _checkForUpdates() async {
    try {
      // 假设你有一个API端点返回应用版本信息
      String updateUrl = "https://your-app-url.com/version.json";
      bool isUpdateAvailable = await _updateAvailable.checkForUpdate(
        currentVersion: "1.0.0", // 当前应用版本
        updateUrl: updateUrl,
      );

      if (isUpdateAvailable) {
        showUpdateDialog();
      }
    } catch (e) {
      print("Error checking for updates: $e");
    }
  }

  void showUpdateDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Update Available"),
          content: Text("A new version of the app is available. Please update."),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                // 打开应用商店页面或下载链接
                _openAppStore();
              },
              child: Text("Update Now"),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text("Later"),
            ),
          ],
        );
      },
    );
  }

  void _openAppStore() {
    // 根据平台打开应用商店页面
    if (Platform.isAndroid) {
      // 对于Android,可以使用play store的URL
      String playStoreUrl = "market://details?id=com.example.yourapp";
      _launchURL(playStoreUrl);
    } else if (Platform.isIOS) {
      // 对于iOS,可以使用App Store的URL
      String appStoreUrl = "itms-apps://apps.apple.com/app/your-app-name/id123456789";
      _launchURL(appStoreUrl);
    }
  }

  _launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Update Available Example"),
        ),
        body: Center(
          child: Text("Check for updates on app start."),
        ),
      ),
    );
  }
}
  1. 版本信息JSON文件

你的服务器上的version.json文件应该包含最新的应用版本信息,例如:

{
  "version": "1.0.1",
  "download_url": "https://your-app-url.com/your-app-1.0.1.apk", // 仅适用于Android
  "release_notes": "Bug fixes and performance improvements."
}

注意:update_available插件的具体实现可能会要求你按照它的API文档调整代码。上面的代码是一个基本的示例,展示了如何检查更新并显示更新对话框。如果你需要更详细的功能(如显示更新日志),你可能需要阅读插件的官方文档并根据需要进行调整。

此外,对于iOS,你可能需要在Info.plist中添加相应的URL schemes,以确保能够正确打开App Store链接。对于Android,确保你的应用具有打开市场链接的权限。

回到顶部