skip to Main Content

I have Dart only project.

How to print the package name ?

For example:

package:myapp/something.dart

How to print this "myapp" from the Dart program itself ?

In other word, I am reffering to the first line of pubspec.yaml name: myapp

Tried

Platform.script; // => /absolute/path/to/the/script.dart
Directory.current; // => /absolute/path/to/the/working/directory

I found a solution with Dart Mirror using

class DummySelf {}

Then

String currentPackage () {
  final classMirror = reflectClass(DummySelf);
  final b = classMirror.location;
  final c = b.toString().replaceFirst("package:", "").split("/").first;
  return c;
}

But it is a very very very ugly solution, unless someone confirms it is the only solution

2

Answers


  1. add yaml package in project and with the following code you can access the content of the pubspec.yaml

    import 'dart:io';
    import 'package:yaml/yaml.dart';
    
    Future<void> readPubspec() async {
      try {
        // Load the pubspec.yaml file as a string
        final File file = File('pubspec.yaml');
        final String yamlString = file.readAsStringSync();
    
        // Parse the string into a YamlMap
        final YamlMap yamlMap = loadYaml(yamlString);
    
        // Access specific content from the yamlMap
        print('Name: ${yamlMap['name']}');
        print('Version: ${yamlMap['version']}');
        print('Description: ${yamlMap['description']}');
      } catch (e) {
        print('Error reading pubspec.yaml: $e');
      }
    }
    
    
    Login or Signup to reply.
  2. There’s a package that does what your looking for, it’s called package_info_plus

    You can use it like this:

    import ‘package:package_info_plus/package_info_plus.dart’;

    void main() async {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String packageName = packageInfo.packageName;
      print("Package name: $packageName");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search