Static Variables

Static Variables

About

  • Class-Level Storage: Associated with class not instances
  • Shared State: Visible to all instances
  • Memory Efficiency: Single allocation
  • Use Cases: Constants, counters, caches

Main Topics

  1. Basic Declaration

    • Definition: static keyword
    • Example:
      class Counter {
        static int _totalCount = 0;
      }
  2. Constants

    • Definition: Compile-time values
    • Example:
      class MathConstants {
        static const double pi = 3.14159;
      }
  3. Mutable State

    • Definition: Shared modification

    • Example:

      class InstanceTracker {
        static int _count = 0;
      
        InstanceTracker() {
          _count++;
        }
      }
  4. Lazy Initialization

    • Definition: Late initialization

    • Example:

      class Config {
        static late final String _apiKey;
      
        static void init(String key) {
          _apiKey = key;
        }
      }
  5. Visibility

    • Definition: Public vs private
    • Example:
      class Logger {
        static const bool _debug = true;
        static int publicCounter = 0;
      }

How to Use

  • Constants: Use static const
  • Shared State: Track class-level data
  • Configuration: Store app-wide settings
  • Memory: Avoid per-instance duplication

How It Works

  1. Storage: Single memory location
  2. Access: Via class name
  3. Lifetime: Matches program execution
  4. Threading: No built-in synchronization

Example:

class AppSettings {
  static const String appName = 'MyApp';
  static late String apiBaseUrl;
  static int _requestCount = 0;

  static void incrementRequestCount() {
    _requestCount++;
  }
}

Conclusion

Static variables provide efficient class-level storage for constants, counters, and shared configuration. When used judiciously, they can reduce memory usage and provide convenient access to common data without requiring instance creation.