Skip to main content
A private method in Dart is a function associated with an object or library whose visibility is strictly confined to the library (typically the file) in which it is defined. Unlike languages that utilize explicit access modifier keywords (such as private or protected), Dart enforces privacy lexically. A method is designated as private by prefixing its identifier with an underscore (_).

Lexical Scope and Library Privacy

Dart’s privacy model is library-based, not class-based. If a method is marked as private, it cannot be invoked from outside the library where it resides. However, any other class, function, or top-level declaration within the exact same library (file) maintains full access to that private method, regardless of class boundaries.

Syntax

class ExampleClass {
  // Public method: Accessible from any library that imports this class
  void publicMethod() {
    _privateMethod(); // Internal invocation
  }

  // Private method: Accessible only within this specific library (file)
  void _privateMethod() {
    print('Executing private method');
  }
}

Visibility Behavior

File 1: library_a.dart
class ClassA {
  void _restrictedMethod() {
    print('Private to library_a.dart');
  }
}

class ClassB {
  void accessSiblingPrivate() {
    ClassA instanceA = ClassA();
    // VALID: Class B is declared in the same library as Class A.
    // It bypasses class-level encapsulation due to Dart's library-level privacy.
    instanceA._restrictedMethod(); 
  }
}
File 2: main.dart
import 'library_a.dart';

void main() {
  ClassA instanceA = ClassA();
  
  // INVALID: Compilation error. 
  // The method '_restrictedMethod' isn't defined for the class 'ClassA' 
  // because the invocation occurs outside 'library_a.dart'.
  instanceA._restrictedMethod(); 
}

Inheritance and Overriding

Private methods are not inherited by subclasses if the subclass resides in a different library. If a subclass in a separate file defines a method with the same _name, it is treated as an entirely new, distinct method rather than an override of the superclass’s private method.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More