Search code examples
dartreflectiondart-mirrors

How to reflect Dart library name?


Is there a way to reflect specific library properties (like the library name) in Dart? How do you get the library object reference?


Solution

  • First of all, not all Dart libraries have names. In fact, most don't. They used to, but the name isn't used for anything any more, so most library authors don't bother adding a name.

    To do reflection on anything, including libraries, you need to use the dart:mirrors library, which does not exist on most platforms, including the web and Flutter. If you are not running the stand-alone VM, you probably don't have dart:mirrors.

    With dart:mirrors, you can get the program's libraries in various ways.

    library my.library.name;
    
    import "dart:mirrors";
    
    final List<LibraryMirror> allLibraries = 
        [...currentMirrorSystem().libraries.values];
    
    void main() {
      // Recognize the library's mirror in *some* way.
      var someLibrary = allLibraries.firstWhere((LibraryMirror library) => 
         library.simpleName.toString().contains("name"));
      
      // Find the library mirror by its name. 
      // Not great if you don't know the name and want to find it.
      var currentLibrary = currentMirrorSystem().findLibrary(#my.library.name);
      print(currentLibrary.simpleName);
    
      // Find a declaration in the current library, and start from there.
      var mainFunction = reflect(main) as ClosureMirror;
      var alsoCurrentLibrary = mainFunction.function.owner as LibraryMirror;
      print(alsoCurrentLibrary.simpleName);
    }
    

    What are you trying to do, which requires doing reflection?