getPackageVersion function

String getPackageVersion(
  1. String packageName
)

Implementation

String getPackageVersion(String packageName) {
  String packageDirPath = Directory.current.path;
  File pubspecFile = File('$packageDirPath/pubspec.yaml');
  if (!pubspecFile.existsSync()) {
    print('pubspec.yaml file not found.');
    return '';
  }
  String pubspecContent = pubspecFile.readAsStringSync();
  var yaml = loadYaml(pubspecContent);
  var dependencies = yaml['dependencies'];
  if (dependencies != null && dependencies[packageName] != null) {
    var version = dependencies[packageName];
    String versionString = version.toString();
    if (versionString.startsWith('^')) {
      versionString = versionString.substring(1);
    }
    return versionString;
  } else {
    print('$packageName is not a dependency in pubspec.yaml.');
    return '';
  }
}