Skip to main content
A public function in Dart is an executable block of code whose identifier does not begin with an underscore (_), rendering it accessible to any external library that imports its containing library. In Dart, public visibility is the default access level for all function declarations; there is no explicit public access modifier keyword.

Syntax

To declare a public function, define the return type, identifier, and parameters without prefixing the identifier with an underscore.
// Top-level public function
ReturnType functionName(Type parameter) {
  // Function body
  return value;
}

class ExampleClass {
  // Public instance method
  ReturnType methodName(Type parameter) {
    // Method body
    return value;
  }

  // Public static method
  static ReturnType staticMethodName() {
    // Method body
    return value;
  }
}

Visibility Mechanics

Dart enforces encapsulation at the library level rather than the class level.
  1. Default Access: Any function declared without a leading underscore is automatically exported by the library.
  2. Cross-Library Access: Public functions can be invoked by any file that imports the defining file via the import directive.
  3. Identifier Constraints: The visibility is determined strictly by the leading character (prefix) of the function identifier.
    • calculateTotal(): Public (Exported).
    • _calculateTotal(): Private (Library-internal only).

Contexts

Public functions exist in three primary contexts:

1. Top-Level Functions

Functions defined outside of any class scope. These are globally accessible to any importer.
// library_a.dart

// Public: Accessible to any file importing library_a.dart
bool isValid(String input) {
  return input.isNotEmpty;
}

2. Instance Methods

Functions defined within a class that operate on instance data. If the class is public and the method is public, the method can be invoked on any instance of that class.
class Processor {
  // Public: Accessible on any instance of Processor
  void execute() {
    _internalLogic(); // Can call private methods internally
  }

  // Private: Only accessible within this library
  void _internalLogic() {
    // Implementation logic
  }
}

3. Static Methods

Functions defined within a class using the static keyword. These are accessed via the class name itself.
class Utils {
  // Public: Accessed via Utils.convert()
  static String convert(int value) {
    return value.toString();
  }
}

Interface Implementation

When a class implicitly implements an interface, all public methods of the class become part of that interface. Private methods (prefixed with _) are excluded from the public interface and do not require implementation by subclasses or implementing classes outside the defining library.
Master Dart with Deep Grasping Methodology!Learn More