Search code examples
flutterdartpackage

Dart Package - How to hide internal methods and classes?


I am developing a package for Flutter Apps

There are methods and classes that are useful only for the package itself, and not for the programmer who will import my package, is possible to hide this methods and classes for further implementation?

Example:

DataService.dart

export class DataService{

    //Must be visible only for my library
    static notifyDataChanged(InternalEvent internalEvent){ ... }

    //Must be visible for anyone
    static addCallbackOnDataChange(onDataChangeCallback) { ... }

}

InternalEvent.dart

//Must be visible only for my library as well
export class InternalEvent {
   ...
}

Solution

  • The usual approach to having package-only declarations is to put them in a library in the lib/src/ directory, and not export that library. The other libraries in the package can import the package-only library, but users outside the package are discouraged from importing libraries in lib/src/ directly. (It's not impossible, just something that's discouraged because the package is free to change those libraries without warning).

    If the package-only features require access to library private parts of public classes, then they need to be in the same library. The traditional way is then to declare both in a library in lib/src/ and export only the parts of that library which needs to be public:

    library myPackage;
    export "src/allDeclarations.dart" hide Private, Declarations;
    // or, preferably, 
    export "src/allDeclarations.dart" show Public, Things;
    

    Generally you should only put exported and non-exported declarations in the same library if absolutely necessary. Otherwise the hide/show lists become too cumbersome and it's to easy to forget a declaration in a hide list.