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

  1. Basic Syntax

    • Definition: static keyword
    • Example:
      class StringUtils {
        static bool isBlank(String? s) {
          return s?.trim().isEmpty ?? true;
        }
      }
  2. 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);
      }
  3. Pure Functions

    • Definition: No side effects
    • Example:
      static double calculateArea(double radius) {
        return pi * radius * radius;
      }
  4. Private Statics

    • Definition: Internal helpers
    • Example:
      static String _generateId() {
        return 'id_${DateTime.now().millisecondsSinceEpoch}';
      }
  5. 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

  1. Invocation: Via class name
  2. Scope: No instance access
  3. Performance: Like top-level functions
  4. 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.