Static Methods & Fields
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 20 of 110.
Now that you understand the difference between instance and static members, let's explore how to use static methods and fields effectively. Static members are perfect for functionality that belongs to the class concept itself rather than to individual objects.
Static fields store data shared across all instances. Common uses include counters, configuration values, or cached data:
class MathHelper {
static const double pi = 3.14159;
static int calculationCount = 0;
static double circleArea(double radius) {
calculationCount++;
return pi * radius * radius;
}
}
print(MathHelper.circleArea(5)); // 78.53975
print(MathHelper.circleArea(3)); // 28.27431
print(MathHelper.calculationCount); // 2Notice that you call static methods directly on the class name, not on an instance. The MathHelper class works like a utility - you never need to create a MathHelper object.
An important rule: static methods cannot access instance members directly. They don't have access to this because they're not tied to any specific object:
class Counter {
int value = 0; // Instance field
static int total = 0; // Static field
void increment() {
value++; // OK - instance method accessing instance field
total++; // OK - instance method can access static field
}
static void reset() {
total = 0; // OK - static method accessing static field
// value = 0; // Error! Can't access instance field
}
}Use static members when the functionality doesn't depend on object state - utility functions, factory tracking, or shared constants are ideal candidates.
Challenge
EasyLet's build a utility class for string operations that demonstrates how static methods and fields work together to provide helpful functionality without needing to create objects.
You'll create two files to organize your code:
string_utils.dart: Define aStringUtilsclass that serves as a utility helper. Your class should have:- A
static const String defaultSeparatorset to'-' - A
static int operationCountstarting at0to track how many operations have been performed - A static method
reverse(String text)that incrementsoperationCountand returns the reversed string - A static method
join(String first, String second)that incrementsoperationCountand returns the two strings joined withdefaultSeparator - A static method
countVowels(String text)that incrementsoperationCountand returns the count of vowels (a, e, i, o, u - case insensitive) - A static method
getStats()that returns a string showing the total operations performed
- A
main.dart: Import your utility class and use its static methods:- Call
reverse()with'hello'and print the result - Call
join()with'dart'and'lang'and print the result - Call
countVowels()with'Programming'and printVowels: [count] - Print the stats using
getStats()
- Call
Remember to call all methods directly on the class name since they're static - you won't create any StringUtils objects.
The getStats() method should return in this format:
Operations performed: [operationCount]Expected output:
olleh
dart-lang
Vowels: 3
Operations performed: 3Cheat sheet
Static members belong to the class itself rather than to individual instances. Access them using the class name, not an object.
Static fields store data shared across all instances:
class MathHelper {
static const double pi = 3.14159;
static int calculationCount = 0;
static double circleArea(double radius) {
calculationCount++;
return pi * radius * radius;
}
}
print(MathHelper.circleArea(5)); // 78.53975
print(MathHelper.calculationCount); // 1Access rules:
- Instance methods can access both instance and static members
- Static methods can only access static members (no access to
this)
class Counter {
int value = 0; // Instance field
static int total = 0; // Static field
void increment() {
value++; // OK - instance method accessing instance field
total++; // OK - instance method can access static field
}
static void reset() {
total = 0; // OK - static method accessing static field
// value = 0; // Error! Can't access instance field
}
}Use static members for utility functions, shared constants, counters, or functionality that doesn't depend on object state.
Try it yourself
import 'string_utils.dart';
void main() {
// TODO: Call reverse() with 'hello' and print the result
// TODO: Call join() with 'dart' and 'lang' and print the result
// TODO: Call countVowels() with 'Programming' and print "Vowels: [count]"
// TODO: Print the stats using getStats()
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor