Access to pubspec.yaml attributes (version) from Dart app

前端 未结 4 1766
孤街浪徒
孤街浪徒 2020-12-06 02:05

Is there any way to access some of the attributes listed in a pubspec.yaml file in that files Dart application?

In particular, the version and description attribute

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 02:21

    you can install the "dart_config" package and use this code to parse a pubspec.yaml file:

    import 'package:dart_config/default_server.dart';
    import 'dart:async';
    
    void main() {
      Future 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']);
      });
    }
    

    The output looks similar to this:

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

    EDIT

    You can do it with the Yaml package itself:

    *NOTE: this will not work on 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

提交回复
热议问题