访问pubspec.从Dart应用程序的yaml属性(版本)



是否有办法访问pubspec中列出的一些属性?该文件中的Dart应用程序中的yaml文件?

特别是,版本和描述属性可能非常有用,可以在版本信息对话框中看到,甚至可以在使用控制台应用程序时使用"——version"。我还没能找到在API中访问的方法。我不确定镜像是否有任何合适的东西,但如果一个web应用程序被编译成JS,那么我在输出JS中看不到任何地方的描述。

谢谢。

编辑
功能请求:https://code.google.com/p/dart/issues/detail?id=18769

仅用于扑动

请使用来自flutter社区的新包package_info_plus

import 'package:package_info_plus/package_info_plus.dart';
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;

我知道OP想要阅读YAML,但对于flutter开发人员来说,你们可以使用package_info阅读应用程序的版本和其他信息。

这是从Android/iOS应用程序中获取细节的示例。

import 'package:package_info/package_info.dart';
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;

可以安装"dart_config"包并使用此代码解析pubspec。yaml文件:

import 'package:dart_config/default_server.dart';
import 'dart:async';
void main() {
  Future<Map> conf = loadConfig("../pubspec.yaml");
  conf.then((Map config) {
    print(config['name']);
    print(config['description']);
    print(config['version']);
    print(config['author']);
    print(config['homepage']);
    print(config['dependencies']);
  });
}

输出如下:

test_cli
A sample command-line application
0.0.1
Robert Hartung
URL
{dart_config: any}

编辑

您可以使用Yaml包本身:

*注意:这在Flutter Web上不起作用

import 'package:yaml/yaml.dart';
import 'dart:io'; // *** NOTE *** This will not work on Flutter Web
void main() {      
    File f = new File("../pubspec.yaml");
    f.readAsString().then((String text) {
      Map yaml = loadYaml(text);
      print(yaml['name']);
      print(yaml['description']);
      print(yaml['version']);
      print(yaml['author']);
      print(yaml['homepage']);
      print(yaml['dependencies']);
    });
}

Regards Robert

以上答案都不适合我,但这里有一个Flutter应用程序的工作解决方案:

在你的pubspec。添加"pubspec.yaml"资产:

assets:
  - assets/
  - pubspec.yaml

如果你有一个小部件,你需要像这样显示应用程序的版本:

...
Container(
  child: Text('Version: 1.0.0+1'),
),
...

像这样用FutureBuilder包装你的小部件:

import 'package:flutter/services.dart';
import 'package:yaml/yaml.dart';
...
        FutureBuilder(
            future: rootBundle.loadString("pubspec.yaml"),
            builder: (context, snapshot) {
              String version = "Unknown";
              if (snapshot.hasData) {
                var yaml = loadYaml(snapshot.data);
                version = yaml["version"];
              }
              return Container(
                child: Text(
                  'Version: $version'
                ),
              );
            }),
...

services rootBundle属性包含了在构建应用程序时打包的资源。

如果你想显示版本而不包含版本号,你可以这样分割字符串:

'Version: ${version.split("+")[0]}'

UPDATE:正如@wildsurfer所提到的,这种方法在web开发中有潜在的安全风险,因为pubspec。与浏览器共享Yaml !

所以假设这是一个dart cli应用程序,那么@Robert建议将不起作用。

dart_config不可用于dart 2。X和你的pubspec。Yaml与CWD无关除非是在开发环境中

所以你需要得到pubspec。与库的可执行路径相对。

这个例子使用了'paths'包,但不是必需的。

可通过以下方式获得:

import 'package:path/path.dart'; 
String pathToYaml =  join(dirname(Platform.script.toFilePath()), '../pubspec.yaml');

您现在可以读取yaml:

import 'package:path/path.dart'; 
import 'package:yaml/yaml.dart';
String pathToYaml = join(dirname(Platform.script.toFilePath()), '../pubspec.yaml');
File f = new File(pathToYaml);
String yamlText =   f.readAsStringSync();
      Map yaml = loadYaml(yamlText);
      print(yaml['name']);
      print(yaml['description']);
      print(yaml['version']);
      print(yaml['author']);
      print(yaml['homepage']);
      print(yaml['dependencies']);
    });                                       

您可以使用Dart团队提供的官方pubspec_parse包访问pubspec.yaml属性。

dart pub add pubspec_parse
import 'dart:io';
import 'package:pubspec_parse/pubspec_parse.dart';
final pubspec = File('pubspec.yaml').readAsStringSync();
final parsed = Pubspec.parse(pubspec);

然后可以访问parsed对象上的类型化属性。

您可以在这里找到支持的属性:https://pub.dev/documentation/pubspec_parse/latest/pubspec_parse/Pubspec-class.html.

仅适用于Flutter (Web, AndroidIOS)…自2020年10月起

如果你想让你的应用程序工作在 Web AndroidIOS使用"Package info_plus"div。

如何将自动版本信息合并到Dart命令行应用程序

要更新代码中的版本信息,而不必在运行时打包资源文件进行解析,您可以将信息硬编码到自动生成的dart源文件中,该文件将被编译成二进制文件。下面的示例将版本、名称和描述信息硬编码到Map对象"元"中。meta.dart文件。每次在开发中运行测试套件时,都会重新创建并覆盖meta.dart文件。为了验证源代码具有正确的版本信息,应用程序的代码根据pubspec中的属性验证版本和其他元信息。Yaml文件(但仅在开发中作为解释代码运行时)。如果与pubspec有区别。Yaml,它抛出一个异常。一旦编译成二进制文件,它就会跳过这个检查,因为它找不到pubspec。Yaml文件,因此不会从二进制抛出错误。即使是公共规范。Yaml文件恰好存在并且被找到,它只抛出一个异常,而不创建一个"meta.dart"源文件。

1。创建一个metupdate类并将其保存为"meta_update.dart":

import 'dart:io';
import 'package:yaml/yaml.dart';
import 'meta.dart';
class MetaUpdate {
  String pathToYaml = "";
  String metaDartFileContents = "";
  MetaUpdate(this.pathToYaml);
  void writeMetaDartFile(String metaDartFilePath) {
    File metaDartFile = File(metaDartFilePath);
    String metaDartFileContents = """
/// DO NOT EDIT THIS FILE EXCEPT TO ENTER INITIAL VERSION AND OTHER META INFO 
/// THIS FILE IS AUTOMATICALLY OVER WRITTEN BY MetaUpdate 
Map<String, String> meta = <String, String>{
  "name": "${getPubSpec('name')}",
  "description":
      // ignore: lines_longer_than_80_chars
      "${getPubSpec('description')}",  
  "version":"${getPubSpec('version')}",
};
  """;
    metaDartFile.writeAsStringSync(metaDartFileContents);
  }
  String getPubSpec(String pubSpecParam) {
    File f = File(pathToYaml);
    String yamlText = f.readAsStringSync();
    // ignore: always_specify_types
    Map yaml = loadYaml(yamlText);
    return yaml[pubSpecParam];
  }
  void verifyLatestVersionFromPubSpec() {
    try {
      File f = File(pathToYaml);
      //exit if no pubspec found so no warning in production
      if (!f.existsSync()) return;
      //compare meta.dart with pubspec meta and give warning if difference
      if (meta.keys
          .where((dynamic e) => (meta[e] != getPubSpec(e)))
          .isNotEmpty) {
        throw Exception(
            """Version number and other meta attributes in code are different from pubspec.yaml.  Please check pubspec.yaml and then run test so that MetaUpdate can update meta information in code, then recompile""");
      }
    } on Exception {
      rethrow;
    }
  }
}

2。创建一个"元数据"。文件:

/// DO NOT EDIT THIS FILE EXCEPT TO ENTER INITIAL VERSION AND OTHER META INFO 
/// THIS FILE IS AUTOMATICALLY OVER WRITTEN BY MetaUpdate 
Map<String, String> meta = <String, String>{
  "name": "Acme Transmogrifier",
  "description":      
      "The best dart application ever.",  
  "version":"2021.09.001",
};

当您最初创建meta.dart文件时,从pubspec.yaml复制您的特定信息。以后每次运行metauupdate . writemetadartfile()时,都会覆盖此内容,每当在pubspec中包含信息时,都会更改内容。

3。在测试代码中实现版本更新

在测试代码的Main()的第一行添加以下代码(不是主程序的源代码,我们不希望它被编译成二进制文件),将路径更改为meta。

MetaUpdate("pubspec.yaml").writeMetaDartFile("lib/src/meta.dart");

4。在主代码中添加元检查

把这个放在你的应用程序的代码,所以它是第一个方法执行时,你的应用程序运行-它会产生一个异常,如果有不同的属性在meta中显示。Dart and pubspec.yaml:

    MetaUpdate("pubspec.yaml").verifyLatestVersionFromPubSpec();

5。使用

  • 确保pubspec中的名称、版本和描述信息。yaml包含您希望在代码中反映的最新信息。
  • 进口"meta.dart"并在需要显示的地方插入meta['name'], meta['version']等(例如,在打印到控制台的——help或——version消息中)。
  • 只要在编译代码之前运行测试,元信息就会准确地反映在代码中。

最新更新