Search code examples
dartlibrariesprivacy

Breaking a library into parts and privacy in Dart


I'm trying to break down a library into parts, and having trouble accessing private elements of the library from a part.

For example, say I have a file named stack.dart with the following content:

library stack;

final _stack = [];

get isEmpty => _stack.isEmpty;
get top => isEmpty ? throw "Empty stack!" : _stack.last;
get pop => isEmpty ? throw 'Empty stack!' : _stack.removeLast();
push(elt){
  _stack.add(elt);
  return elt;
}

I also have another file with the following contents:

part of stack;

display(){
  print(_stack); // can't access _stack from here!
}

Is this to be expected or am I doing something wrong?

Is _stack private to the library or the file?


Solution

  • Your problem is you have forgotten to include you file into the library by using the part keyword:

    lib.dart:

    library test_lib;
    part 'part.dart';
    
    final _private = 'This is private';
    

    part.dart:

    part of test_lib;
    
    void test() {
      print(_private); // I have access to the _private variable defined in lib.dart
    }