Skip to main content
A private function in Dart is a function or method whose visibility is strictly limited to the library in which it is declared. Dart enforces privacy through identifier syntax rather than explicit access modifier keywords (such as private or protected).

Syntax

To mark a function as private, prefix the function identifier with an underscore (_). This rule applies to top-level functions, static methods, and instance methods.
// Top-level private function
void _internalCalculation() {
  print("Calculated internally");
}

class Processor {
  // Private instance method
  void _logProcess() {
    print("Processing...");
  }
}

Library-Level Scope

In Dart, the unit of privacy is the library (typically a single .dart file), not the class.
  1. Same Library Access: Any code within the same library (file) can access private functions, even if they belong to different classes or are top-level definitions.
  2. External Library Access: Code importing the library cannot access identifiers starting with _.

Implementation Example

File: utils.dart (The Library)
library utils;

// Public function
void publicStart() {
  _privateHelper(); // Valid: Accessing private function within same library
}

// Private function
void _privateHelper() {
  print("Helper executed");
}

class Worker {
  void _doWork() => print("Working");
}

void accessCrossClass() {
  // Valid: Accessing private member of a class within the same library
  Worker w = Worker();
  w._doWork(); 
}
File: main.dart (The Importer)
import 'utils.dart';

void main() {
  publicStart(); // Valid: Public function is accessible
  
  // _privateHelper(); // Compilation Error: The function is not defined for the current library
  
  Worker w = Worker();
  // w._doWork(); // Compilation Error: The method '_doWork' isn't defined for the class 'Worker'
}

Runtime Behavior

The privacy restriction is enforced by the Dart analyzer and compiler. Attempting to call a private function from an external library results in a compilation error stating that the method or function is not defined. At runtime, the symbol exists but is effectively unreachable from outside scopes due to name mangling or access checks depending on the compilation target (AOT/JIT).
Master Dart with Deep Grasping Methodology!Learn More