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

前端 未结 4 1768
孤街浪徒
孤街浪徒 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:06

    So assuming that this is for a dart cli application then the @Robert suggestion won't work.

    dart_config isn't available for dart 2.x and your pubspec.yaml isn't going to be relative to your cwd except when you are in your development environment

    So you need to get the pubspec.yaml relative to the libraries executable path.

    This example uses the 'paths' package but it isn't required.

    This can be obtained by:

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

    You can now read the 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']);
        });                                       
    

提交回复
热议问题