Public and Private Members

Public and Private Members

About

  • Public Members: Visible to all code (default)
  • Private Members: Visible only within library (_ prefix)
  • Applies to class fields, methods, top-level variables
  • Essential for encapsulation

Main Topics

  1. Public Access

    • Definition: Default visibility
    • Example:
      class User {
        String name; // Public by default
      }
  2. Private Members

    • Definition: _ prefix convention
    • Example:
      class User {
        String _id; // Private to library
      }
  3. Method Visibility

    • Definition: Applying to methods

    • Example:

      class Calculator {
        int _current = 0;
      
        void _reset() { // Private method
          _current = 0;
        }
      }
  4. Top-level Privacy

    • Definition: Outside classes
    • Example:
      String publicVar = 'visible';
      String _privateVar = 'hidden';
  5. Getter/Setter Control

    • Definition: Exposing private fields

    • Example:

      class Wallet {
        double _balance = 0;
      
        double get balance => _balance; // Public read-only
      }

How to Use

  • Encapsulation: Hide implementation details
  • API Design: Expose only what’s needed
  • Naming: _ prefix for private members
  • Testing: Use library structure for access

How It Works

  1. Compilation: _ prefix triggers privacy
  2. Scope: Library boundary enforcement
  3. Visibility: Analyzer enforces access rules
  4. Tooling: IDE shows visibility cues

Example:

class BankAccount {
  String _accountNumber; // Private
  double balance = 0;    // Public

  BankAccount(this._accountNumber);

  void _logTransaction() { // Private
    print('Transaction for $_accountNumber');
  }
}

Conclusion

Dart’s public/private access control through naming conventions provides a simple yet effective way to manage encapsulation. By prefixing members with _, developers can hide implementation details while exposing clean public APIs, leading to more maintainable code.