Flutter应用版本获取插件application_version的使用

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

Flutter应用版本获取插件application_version的使用

Pub

特性

  • 获取应用版本:检索应用的版本和构建号。
  • VersionData 类
    • 解析:解析版本字符串并确保语义化版本(例如,“1.0”变为“1.0.0”)。
    • 比较:实现 Comparable<VersionData> 接口以进行版本比较。
    • 相等性:重写 ==hashCode 以便正确检查相等性和在集合中使用。
    • 字符串表示形式:提供 toString 方法以可读格式显示版本。

为什么创建这个项目?

许多开发者使用 package_info 包,它提供了广泛的功能。然而,package_info 的广泛功能伴随着许多依赖项,这些依赖项可能会与其他包冲突。因此,创建了这个小包来仅做一件事:显示应用程序的版本。它的目标是轻量级且依赖项最少,从而减少冲突的风险。

安装

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

dependencies:
  application_version: "^0.0.1"

如何使用

在你的 Dart 文件中导入以下包:

import 'package:application_version/application_version.dart';

然后你可以这样获取版本信息:

VersionData? version = await ApplicationVersion.getVersion();

VersionData 类

VersionData 类包含用于比较的方法,这在从后端接收最低要求版本时可能很有用。

final version1 = VersionData.parse('1.2+100');
final version2 = VersionData.parse('1.2.0+101');
final version3 = VersionData.parse('1.3');
final version4 = VersionData.parse('1.2.0');

print(version1 < version2); // true
print(version1 > version3); // false
print(version2 >= version1); // true
print(version3 <= version2); // false
print(version1 == version4); // true 

// 忽略构建号的比较
print(version1 == version4); // true 

// 检查当前版本是否符合最低要求版本
final currentVersion = VersionData.parse('2.0.1');
final minRequiredVersion = VersionData.parse('2.0.0');

if (currentVersion >= minRequiredVersion) {
  print('Current version meets the minimum required version.');
} else {
  print('Current version does not meet the minimum required version.');
}

示例代码

import 'package:application_version/version_data.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:application_version/application_version.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  VersionData? _version;

  [@override](/user/override)
  void initState() {
    super.initState();
    initVersionState();
  }

  Future<void> initVersionState() async {
    VersionData? version;

    try {
      version = await ApplicationVersion.getVersion();
    } on PlatformException {
      version = null;
    }

    // 如果在异步平台消息飞行期间小部件被从树中移除,我们想丢弃回复而不是调用 setState 更新不存在的外观。
    if (!mounted) return;

    setState(() {
      _version = version;
    });
  }

  final v1 = VersionData.parse('0.0.1');
  final v2 = VersionData.parse('1.0.0');
  final v3 = VersionData.parse('1.0.0+2');
  final v4 = VersionData.parse('1.0.2');

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件应用版本'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('运行于: $_version\n'),
              if (_version != null) ...[
                Text('版本: ${_version!.semantic}\n'),
                Text('构建号: ${_version!.buildNumber}\n'),
                Text('$v1 > $_version: ${v1 > _version!}\n'),
                Text('$v2 == $_version: ${v2 == _version!}\n'),
                Text('$v3 > $_version: ${v3 > _version!}\n'),
                Text('$v4 > $_version: ${v4 > _version!}\n'),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用application_version插件来获取应用版本信息的示例代码。

首先,确保你的Flutter项目中已经添加了application_version插件。你可以通过修改pubspec.yaml文件来添加该插件:

dependencies:
  flutter:
    sdk: flutter
  application_version: ^2.0.0  # 请检查最新版本号

然后运行flutter pub get来安装该插件。

接下来,在你的Flutter应用中,你可以使用以下代码来获取应用版本信息:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _appName;
  String _packageName;
  String _versionName;
  String _versionCode;
  String _buildNumber;

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

  Future<void> _getApplicationVersion() async {
    ApplicationVersion versionInfo = await ApplicationVersion.getVersion();
    setState(() {
      _appName = versionInfo.appName;
      _packageName = versionInfo.packageName;
      _versionName = versionInfo.versionName;
      _versionCode = versionInfo.versionCode.toString();
      _buildNumber = versionInfo.buildNumber.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Application Version Info'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('App Name: $_appName'),
            Text('Package Name: $_packageName'),
            Text('Version Name: $_versionName'),
            Text('Version Code: $_versionCode'),
            Text('Build Number: $_buildNumber'),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,并在应用启动时获取应用的版本信息。我们通过ApplicationVersion.getVersion()方法获取版本信息,然后在UI中显示这些信息。

请注意,ApplicationVersion类提供的字段可能因平台而异。例如,versionCodebuildNumber在某些平台上可能不适用。因此,在实际开发中,你可能需要根据平台差异进行适当的处理。

希望这个示例能帮助你更好地理解如何在Flutter应用中使用application_version插件来获取应用版本信息。

回到顶部