Static Methods
Static Methods
About
- Class Operations: Not instance-specific
- No
this
: Cannot access instance members - Utility Functions: Common use case
- Factory Patterns: Alternative constructors
Main Topics
-
Basic Syntax
- Definition:
static
keyword - Example:
class StringUtils { static bool isBlank(String? s) { return s?.trim().isEmpty ?? true; } }
- Definition:
-
Factory Constructors
-
Definition: Alternative instantiation
-
Example:
class Image { final String _path; static final _cache = <String, Image>{}; factory Image(String path) { return _cache.putIfAbsent(path, () => Image._internal(path)); } Image._internal(this._path); }
-
-
Pure Functions
- Definition: No side effects
- Example:
static double calculateArea(double radius) { return pi * radius * radius; }
-
Private Statics
- Definition: Internal helpers
- Example:
static String _generateId() { return 'id_${DateTime.now().millisecondsSinceEpoch}'; }
-
Utility Classes
-
Definition: Collections of statics
-
Example:
class MathHelpers { static double lerp(double a, double b, double t) { return a + (b - a) * t; } // Prevent instantiation MathHelpers._(); }
-
How to Use
- Utilities: Group related functions
- Factories: Control object creation
- Helpers: Reusable computations
- Organization: Logical grouping
How It Works
- Invocation: Via class name
- Scope: No instance access
- Performance: Like top-level functions
- Visibility: Follows normal rules
Example:
class DateTimeUtils {
static DateTime get firstOfNextMonth {
final now = DateTime.now();
return DateTime(now.year, now.month + 1, 1);
}
static String formatDuration(Duration d) {
return '${d.inHours}h ${d.inMinutes.remainder(60)}m';
}
}
Conclusion
Static methods provide class-level functionality that doesn’t depend on instance state. They’re ideal for utility functions, factory patterns, and pure computations, helping to organize code logically while avoiding unnecessary object instantiation.