Flutter应用更新管理插件update_center的使用
Flutter应用更新管理插件update_center的使用
介绍
Update Center 是一个 Flutter 插件,允许你在不同平台上(如 Android 和 Windows)实现多平台的应用更新检查。以下是该插件的主要功能:
- 自定义对话框:根据你的应用风格创建自己的对话框。
 - 自动更新检查:根据运行平台自动检查更新。
 - 防止跳过更新:如果 JSON 文件中的版本号高于本地版本号,插件会阻止用户关闭对话框。
 - 文件管理:插件可以处理下载的文件,并在更新完成后删除旧文件。如果用户未更新且有新版本发布,插件会删除旧文件并下载新文件,而不是重新启动下载。
 - 支持多种文件格式:Windows 支持 zip 和 exe 文件,Android 类似。
 - 灵活配置:插件提供了多种可自定义的设置。
 
快速开始
添加依赖
首先,在 pubspec.yaml 文件中添加 update_center 依赖:
dependencies:
  update_center: ^2.0.1
JSON 文件结构
插件通过 JSON 文件来获取更新信息。以下是一个示例 JSON 文件结构:
{
  "android": {
    "versionName": "1.1.0",
    "downloadUrl": "https://example.com/UpdateCenter/app.apk",
    "changeLog": "- bug fixed; \n- new ui;",
    "sourceUrl": "https://example.com/",
    "versionCode": 2,
    "minSupport": 1
  },
  "windows": {
    "versionName": "5.0.0",
    "downloadUrl": "https://example.com/UpdateCenter/app-windows.exe",
    "changeLog": "- Bug fixes and performance improvements. \n- New Icon;",
    "sourceUrl": "https://example.com/",
    "versionCode": 34,
    "minSupport": 14
  }
}
JSON 结构说明
versionName:新的版本名称。downloadUrl:下载新版本 APK 或 EXE 文件的 URL。changeLog:更新日志,描述新版本的变化。sourceUrl:更多关于更新的信息或源代码的 URL。versionCode:新的版本号。minSupport:最低支持的版本号,低于此版本号的设备将被强制更新。
示例代码
初始化和配置插件
Android 权限
首先,确保在 AndroidManifest.xml 中添加以下权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
完整的插件设置
以下是完整的插件初始化和配置示例代码:
import 'package:flutter/material.dart';
import 'package:update_center/update_center.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  late UpdateCenter updateCenter;
  static const String _apiUrl = 'https://example.com/UpdateCenter/update_center.json';
  _launchURL(String sourceUrl) async {
    final Uri url = Uri.parse(sourceUrl);
    if (!await launchUrl(url)) {
      throw Exception('Could not launch $sourceUrl');
    }
  }
  [@override](/user/override)
  void initState() {
    initializeUpdateCenter();
    super.initState();
  }
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Update Center v2.0.0'),
        ),
        body: Center(
          child: OutlinedButton(
            onPressed: () => checkUpdate(), // 点击按钮检查更新
            child: const Text('Check update'),
          ),
        ),
      ),
    );
  }
  void initializeUpdateCenter() {
    // 主要插件设置
    updateCenter = UpdateCenter(
      context: context,
      urlJson: _apiUrl, // 获取更新信息的 JSON URL (请替换为你的 URL)
      config: UpdateCenterConfig(
        globalConfig: GlobalConfig(
          checkStart: false, // 是否在应用启动时检查更新
          noUpdateAvailableToast: true, // 如果没有可用更新是否显示 Toast 提示
          sourceUrl: false, // 是否启用点击链接而不是下载文件
          openingFile: true, // 是否打开已下载的文件而不是重新下载
          // 显示没有可用更新的通知
          androidNoUpdateAvailableBuilder: (BuildContext context) {
            Fluttertoast.showToast(msg: 'No updates found');
          },
          windowsNoUpdateAvailableBuilder: (BuildContext context) {
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
              content: Text('No updates found'),
              duration: Duration(seconds: 2),
            ));
          },
          // 构建每个平台的更新对话框
          androidDialogBuilder: (BuildContext context, AndroidModel model, UpdateCenterConfig config, DownloadState downloadState, bool allowSkip) {
            return showDialog(
              context: context,
              barrierDismissible: allowSkip,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text(model.versionName),
                  content: Text(model.changeLog),
                  actions: [
                    if (allowSkip)
                      TextButton(
                        onPressed: () => Navigator.of(context).pop(),
                        child: const Text("Close"),
                      ),
                    // 显示下载进度
                    ValueListenableBuilder<bool>(
                      valueListenable: downloadState.isDownloading,
                      builder: (context, isDownloading, child) {
                        return TextButton(
                          onPressed: isDownloading
                              ? null
                              : () async {
                                  downloadState.isDownloading.value = true;
                                  // 确保下载时按钮不可用
                                  await OnDownload.initiateUpdate(
                                    url: model.downloadUrl,
                                    versionName: model.versionName,
                                    config: config,
                                    downloadState: downloadState,
                                    sourceUrl: model.sourceUrl,
                                    launchUrl: (url) => _launchURL(url),
                                  );
                                },
                          child: isDownloading
                              ? ValueListenableBuilder<double>(
                                  valueListenable: downloadState.progress,
                                  builder: (context, progress, _) {
                                    int progressValue = (progress * 100).toInt();
                                    return AnimatedFlipCounter(
                                      suffix: '%',
                                      duration: const Duration(milliseconds: 500),
                                      value: progressValue,
                                      textStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface),
                                    );
                                  },
                                )
                              : const Text('Download'),
                        );
                      },
                    )
                  ],
                );
              },
            );
          },
          windowsDialogBuilder: (BuildContext context, WindowsModel model, UpdateCenterConfig config, DownloadState downloadState, bool allowSkip) {
            return showDialog(
              context: context,
              barrierDismissible: allowSkip,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text(model.versionName),
                  content: Text(model.changeLog),
                  actions: [
                    if (allowSkip)
                      TextButton(
                        onPressed: () => Navigator.of(context).pop(),
                        child: const Text("Close"),
                      ),
                    // 显示下载进度
                    ValueListenableBuilder<bool>(
                      valueListenable: downloadState.isDownloading,
                      builder: (context, isDownloading, child) {
                        return TextButton(
                          onPressed: isDownloading
                              ? null
                              : () async {
                                  downloadState.isDownloading.value = true;
                                  // 确保下载时按钮不可用
                                  await OnDownload.initiateUpdate(
                                    url: model.downloadUrl,
                                    versionName: model.versionName,
                                    config: config,
                                    downloadState: downloadState,
                                    sourceUrl: model.sourceUrl,
                                    launchUrl: (url) => _launchURL(url),
                                  );
                                },
                          child: isDownloading
                              ? ValueListenableBuilder<double>(
                                  valueListenable: downloadState.progress,
                                  builder: (context, progress, _) {
                                    int progressValue = (progress * 100).toInt();
                                    return AnimatedFlipCounter(
                                      suffix: '%',
                                      duration: const Duration(milliseconds: 500),
                                      value: progressValue,
                                      textStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface),
                                    );
                                  },
                                )
                              : const Text('Download'),
                        );
                      },
                    )
                  ],
                );
              },
            );
          },
        ),
      ),
    );
  }
  // 检查更新 (例如通过按钮触发)
  checkUpdate() async {
    await updateCenter.check();
  }
}
更多关于Flutter应用更新管理插件update_center的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
        
          1 回复
        
      
      
        
        
      
            
            
            

