Static members
suggest changeIn Dart, static variables and static methods belong to the class itself rather than to individual instances of that class. They provide class-level state, constants, and utility methods that do not depend on an instance's this context.
Static Variables and Lazy Initialization
Static variables are declared using the static keyword inside a class body.
A crucial feature of Dart is that static variables are lazily initialized: they are evaluated only when first read, not when the application boots:
class DatabaseConfig {
// Static variable initialized only when first accessed
static String endpoint = _loadEndpoint();
static String _loadEndpoint() {
print('Computing database endpoint...');
return 'https://db.internal.example.com:5432';
}
}
void main() {
print('Application started.');
// _loadEndpoint has not run yet
print('Accessing endpoint:');
print(DatabaseConfig.endpoint); // Prints "Computing database endpoint..." then endpoint
print(DatabaseConfig.endpoint); // Cached, does not re-compute
}
static const for Compile-Time Constants
When a static value is known at compile time, declare it as static const:
class AppConstants {
static const int maxRetryAttempts = 5;
static const String appName = 'InventoryManager';
static const Duration defaultTimeout = Duration(seconds: 15);
// Private constructor prevents instantiation of pure utility classes
AppConstants._();
}
Static Methods
Static methods perform operations that do not require an active instance of the class:
class MathUtils {
// Private constructor prevents instantiation
MathUtils._();
static double celsiusToFahrenheit(double c) => (c * 9 / 5) + 32;
static double fahrenheitToCelsius(double f) => (f - 32) * 5 / 9;
}
void main() {
final boilingF = MathUtils.celsiusToFahrenheit(100);
print('100°C in Fahrenheit: $boilingF°F'); // 212.0°F
}
Static Methods as Tear-Offs
In Dart, you can pass a static method directly as a first-class function pointer (tear-off):
class User {
final String name;
final int age;
User({required this.name, required this.age});
static User fromJson(Map<String, dynamic> json) {
return User(
name: json['name'] as String,
age: json['age'] as int,
);
}
}
void main() {
final rawData = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
];
// Pass User.fromJson directly without wrapping in a lambda:
final users = rawData.map(User.fromJson).toList();
print('Loaded ${users.length} users.');
}
Static Getters and Setters
You can implement custom computation and validation on class-level properties using static getters and setters:
class Environment {
static String _current = 'development';
static String get current => _current;
static set current(String value) {
final valid = ['development', 'staging', 'production'];
if (!valid.contains(value)) {
throw ArgumentError('Invalid environment: $value');
}
_current = value;
}
static bool get isProduction => _current == 'production';
}
void main() {
Environment.current = 'production';
print('Is Production: ${Environment.isProduction}'); // true
}
Key Caveat: Static Members Are Not Inherited
Unlike Java or C#, in Dart subclasses do not inherit static members from their parent class:
class SuperClass {
static void greet() => print('Hello from SuperClass');
}
class SubClass extends SuperClass {}
void main() {
SuperClass.greet(); // Valid
// Compile Error: The method 'greet' isn't defined for the type 'SubClass'
// SubClass.greet();
}
Static members must always be accessed through the exact class type that declared them.
Static Members vs Top-Level Functions
Dart allows top-level functions and variables directly in libraries without wrapping them in classes:
// Preferred in Dart when a function is not tied to a class:
double calculateTax(double subtotal) => subtotal * 0.08;
// Rather than creating a dummy namespace class:
class TaxCalculator {
static double calculateTax(double subtotal) => subtotal * 0.08; // Less idiomatic
}
Use static class members when:
- The member belongs logically to a specific data model (like
User.fromJson). - You need to encapsulate private static state (
_cache,_instance). - Grouping closely related domain operations under a meaningful type name.
Best Practices
- Use
static constfor constants: Reduces memory usage through compile-time canonicalization. - Leverage lazy initialization: Dart static variables initialize on first access, so expensive resource setups do not degrade application startup times.
- Use private constructors (
ClassName._()): If a class only contains static utilities, declare a private constructor to prevent unintentional instantiation. - Prefer top-level functions for general utilities: Follow Dart style conventions and avoid creating artificial "God" utility classes containing unrelated static functions.