Skip to main content
A public field in Dart is a class-level variable that is accessible from any library that imports the class. Unlike languages that rely on explicit access modifier keywords (such as public, private, or protected), Dart determines visibility through lexical naming conventions. Any field whose identifier does not begin with an underscore (_) is implicitly public.

Syntax and Declaration

Public fields can be mutable variables, immutable variables (final), or class-level variables (static). Because Dart does not use a public keyword, the declaration relies solely on the type, the identifier, and optional modifiers.
class Configuration {
  // Public mutable instance field
  String environment;

  // Public immutable instance field (can only be set once)
  final String version;

  // Public static field (belongs to the class, not instances)
  static int maxConnections = 100;

  // Public late-initialized field
  late String databaseUrl;

  Configuration(this.environment, this.version);
}

Technical Characteristics

Implicit Accessors When you declare a public field, the Dart compiler automatically generates implicit accessor methods.
  • For a mutable public field (e.g., String environment), Dart generates both an implicit getter and an implicit setter.
  • For an immutable public field (e.g., final String version), Dart generates only an implicit getter.
When a developer uses dot notation (object.field), they are technically invoking these implicit methods rather than accessing the memory location directly. This allows you to later replace a public field with explicit getter/setter methods without breaking the API or requiring changes to the calling code. Library-Level Scoping Dart’s visibility model is based on library boundaries, not class boundaries. Because a public field lacks the _ prefix, it is exported as part of the library’s public API. Any external Dart file that imports the library can read (and, if mutable, write to) the field. Null Safety Enforcement Under Dart’s sound null safety, public fields must be guaranteed to have a value before they are accessed. A public field must be:
  1. Initialized at the point of declaration.
  2. Initialized in the constructor (via initializing formals or an initializer list).
  3. Declared as nullable using the ? operator (e.g., String? name).
  4. Marked with the late keyword, deferring the initialization check to runtime.

Access Mechanics

Accessing public fields is done using standard dot notation. Instance fields require an instantiated object, while static fields are accessed directly on the class type.
void main() {
  var config = Configuration('Production', '1.0.0');

  // Invoking the implicit setter
  config.environment = 'Staging';

  // Invoking the implicit getter
  print(config.version); 

  // Accessing a public static field via the class type
  print(Configuration.maxConnections);
}
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More