【问题标题】:How to get build and version number of Flutter app如何获取 Flutter 应用的构建和版本号
【发布时间】:2019-05-09 09:01:20
【问题描述】:

我目前正在开发一个目前处于测试模式的应用程序。因此,我想向他们展示他们使用的版本。例如,“v1.0b10 - iOS”。到目前为止,我已经得到了这个代码:Text("Build: V1.0b10 - " + (Platform.isIOS ? "iOS" : "Android"))。我如何能够在颤振中获得构建版本和编号?

【问题讨论】:

标签: flutter version


【解决方案1】:

您可以使用package_info_plus

版本摘自:

安卓:

build.gradle, versionCode and versionName

iOS:

Info.plist, CFBundleVersion

用法

添加依赖

  1. 将此添加到包的 pubspec.yaml 文件中:
dependencies:
  package_info_plus: ^1.0.6
  1. 将文件导入您的 dart 文件:
import 'package:package_info_plus/package_info_plus.dart';
  1. 如果你的方法被标记为async
PackageInfo packageInfo = await PackageInfo.fromPlatform();

String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;

如果你不想使用await/async

PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
  String appName = packageInfo.appName;
  String packageName = packageInfo.packageName;
  String version = packageInfo.version;
  String buildNumber = packageInfo.buildNumber;
});

【讨论】:

  • 在 IOS 中,这个版本是 1.0.0 而不是 1.0.0+6。你能指导我可能是什么问题吗?
  • @Wajidkhan,1.0.0 是版本号,6 是内部版本号。见this
  • 这是否意味着我需要手动修改/维护 iOS 和 Android 的不同版本?有统一的地方吗?
  • 未处理的异常:MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/package_info) 仅在发布 apk 上
  • 如果您希望您的应用在 Web、Android 和 IOS 上运行,请改用“package_info_plus”。 pub.dev/packages/package_info_plus.
【解决方案2】:

注意:此答案已更新,以反映 package_info 插件已弃用并重定向到 package_info_plus 的事实。

版本名称和内部版本号

在开发时,您可以通过检查 pubspec.yaml 轻松找到 Flutter 或 Dart 项目的版本名称和内部版本号。这是一个例子:

version: 1.1.0+2

在这种情况下,版本名称为1.1.0,内部版本号为2

但是,如果您想在运行时获取这些值,您应该使用插件。

添加依赖

pubspec.yaml 中添加 package_info_plus 包。

dependencies:
  package_info_plus: ^1.0.2

将版本号更新为current

导入包

在您需要的文件中,添加以下导入。

import 'package:package_info_plus/package_info_plus.dart';

获取版本名称和代码

在您的代码中,您可以像这样获取应用版本名称和代码:

PackageInfo packageInfo = await PackageInfo.fromPlatform();
String version = packageInfo.version;
String code = packageInfo.buildNumber;

另见

【讨论】:

  • 我看不出这与接受的答案有何不同?
  • @Volleyball,在我回答问题时,接受的答案要短得多(检查编辑历史记录)。后来那个用户添加了很多内容,所以现在基本一样了。
  • 对不起,我没看到,你是对的,你的答案应该是被接受的,我 +1。
  • package_info_plus - 很好。非常感谢分享。比package_info 更喜欢它,因为它支持更多平台。
  • 更多关于不推荐使用的包插件在这里:github.com/flutter/plugins/blob/master/README.md#deprecated
【解决方案3】:

package_info 安装后,您可以直接在您的小部件树中与未来的构建器一起使用它:

 FutureBuilder<PackageInfo>(
              future: PackageInfo.fromPlatform(),
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.done:
                    return Align(
                      alignment: Alignment.bottomCenter,
                      child: Text(
                        'Version: ${snapshot.data!.version}',),
                      );
                  default:
                    return const SizedBox();
                }
              },
            ),

【讨论】:

    【解决方案4】:

    RE 多次引用package_info,请注意此包已被弃用,建议替换为Flutter Community Plus Plugins 版本package_info_plus

    【讨论】:

      【解决方案5】:

      您可以使用get_version查询应用程序版本名称、版本代码、平台和操作系统版本以及iOS和Android上的App ID信息

      将此添加到您的包的pubspec.yaml 文件中:

      dependencies:
        get_version: ^0.2.2
      

      现在在你的 Dart 代码中,你可以使用:

      import 'package:get_version/get_version.dart';
      

      转到build.gradle 并更新:

      defaultConfig {
        versionCode 1
        versionName "1.0"
        minSdkVersion 16
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
      }
      

      如何使用

      class _MyAppState extends State<MyApp> {
        String _platformVersion = 'Unknown';
        String _projectVersion = '';
        String _projectCode = '';
        String _projectAppID = '';
        String _projectName = '';
      
        @override
        initState() {
          super.initState();
          initPlatformState();
        }
      
        // Platform messages are asynchronous, so we initialize in an async method.
        initPlatformState() async {
          String platformVersion;
          // Platform messages may fail, so we use a try/catch PlatformException.
          try {
            platformVersion = await GetVersion.platformVersion;
          } on PlatformException {
            platformVersion = 'Failed to get platform version.';
          }
      
          String projectVersion;
          // Platform messages may fail, so we use a try/catch PlatformException.
          try {
            projectVersion = await GetVersion.projectVersion;
          } on PlatformException {
            projectVersion = 'Failed to get project version.';
          }
      
          String projectCode;
          // Platform messages may fail, so we use a try/catch PlatformException.
          try {
            projectCode = await GetVersion.projectCode;
          } on PlatformException {
            projectCode = 'Failed to get build number.';
          }
      
          String projectAppID;
          // Platform messages may fail, so we use a try/catch PlatformException.
          try {
            projectAppID = await GetVersion.appID;
          } on PlatformException {
            projectAppID = 'Failed to get app ID.';
          }
      
          String projectName;
          // Platform messages may fail, so we use a try/catch PlatformException.
          try {
            projectName = await GetVersion.appName;
          } on PlatformException {
            projectName = 'Failed to get app name.';
          }
      
          // If the widget was removed from the tree while the asynchronous platform
          // message was in flight, we want to discard the reply rather than calling
          // setState to update our non-existent appearance.
          if (!mounted) return;
      
          setState(() {
            _platformVersion = platformVersion;
            _projectVersion = projectVersion;
            _projectCode = projectCode;
            _projectAppID = projectAppID;
            _projectName = projectName;
          });
        }
        
      }
      

      【讨论】:

        【解决方案6】:

        你可以试试new_version插件。使用此插件,您可以获得安装的应用程序版本、Playstore 应用程序版本和可以重定向到 playstore 的应用程序 url。

        New Version Plugin

        void versionCheck() async {
            final NewVersion newVersion = NewVersion(context: context);
            VersionStatus versionStatus = await newVersion.getVersionStatus();
            if (versionStatus != null && versionStatus.canUpdate) {
              await ConfirmDialog(
                  context: context,
                  title: 'Update Available',
                  body: Text('A new version, ${versionStatus.storeVersion}, is available.'),
                  acceptButton: 'Update Now',
                  cancelButton: 'Update Later'
              ).then((ConfirmAction res) async {
                if (res == ConfirmAction.CONFIRM && await canLaunch(versionStatus.appStoreLink)) {
                  await launch(versionStatus.appStoreLink, forceWebView: false);
                }
              });
            }
          }
        

        自定义警报对话框

        enum ConfirmAction{ CONFIRM, CANCEL }
        Future<ConfirmAction> ConfirmDialog({
          BuildContext context,
          String title,
          Widget body,
          String acceptButton,
          String cancelButton
        })
        => showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) => AlertDialog(
              title: Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                spacing: 4,
                children: <Widget>[
                  Text(title)
                ],
              ),
              content: Wrap(
                runSpacing: 10,
                children: <Widget>[
                  body,
                ],
              ),
              actions: <Widget>[
                FlatButton(
                    padding: EdgeInsets.all(6),
                    child: Text(acceptButton ?? 'Confirm'),
                    onPressed: (){
                      Navigator.of(context, rootNavigator: true).pop(ConfirmAction.CONFIRM);
                    }
                ),
                FlatButton(
                    padding: EdgeInsets.all(6),
                    child: Text(cancelButton ?? 'Cancel'),
                    onPressed: (){
                      Navigator.of(context, rootNavigator: true).pop(ConfirmAction.CANCEL);
                    }
                ),
              ],
            )
        );
        

        【讨论】:

          猜你喜欢
          • 2020-06-24
          • 2019-06-18
          • 2019-03-04
          • 2011-09-29
          • 1970-01-01
          • 1970-01-01
          • 2011-11-21
          • 2022-01-02
          相关资源
          最近更新 更多