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
-
Basic Declaration
- Definition:
static
keyword - Example:
class Counter { static int _totalCount = 0; }
- Definition:
-
Constants
- Definition: Compile-time values
- Example:
class MathConstants { static const double pi = 3.14159; }
-
Mutable State
-
Definition: Shared modification
-
Example:
class InstanceTracker { static int _count = 0; InstanceTracker() { _count++; } }
-
-
Lazy Initialization
-
Definition: Late initialization
-
Example:
class Config { static late final String _apiKey; static void init(String key) { _apiKey = key; } }
-
-
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
- Storage: Single memory location
- Access: Via class name
- Lifetime: Matches program execution
- 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.