tezvyn:

Static Members: Belong to the Class, Not the Instance

AI-drafted, machine-checkedSource: dart.devbeginner

A static member is shared across all instances of a class, belonging to the class itself. Use it for constants or utility functions that don't depend on an instance's state, like a global counter. The footgun: you cannot use `this` inside a static context.

WHY IT EXISTS Sometimes you need functionality or data that is associated with a class conceptually but doesn't need to be duplicated for every single object created from that class. Storing a shared counter or a utility function on each instance would be wasteful and illogical. Static members solve this by providing a single, shared home on the class itself.

THE MENTAL MODEL Think of a school. Each student object (an instance) has their own studentID and lockerNumber (instance variables). But the school's main office phone number is the same for everyone. That phone number is a static variable on the School class. You'd access it via School.mainPhoneNumber, not someStudent.mainPhoneNumber.

HOW IT WORKS The static keyword in Dart marks a member (a variable or a method) as belonging to the class, not to instances of the class. You access static members directly using the class name, like ClassName.staticMember. Because they aren't tied to an instance, static methods cannot access instance variables or methods, including the this keyword, which refers to the current instance. They can, however, access other static members of the same class.

WHEN TO USE IT Use static members for three main scenarios. First, for constants that are intrinsic to the class, like Math.pi. Second, for helper or utility functions that operate on inputs without needing any internal state, like a StringUtils.capitalize() method. Third, to manage a state that is shared across all instances of the class, such as a singleton instance or a global cache.

WHEN NOT TO USE IT Do not use a static member if the data or behavior is specific to an individual object. A car's color, a user's email, or a document's content are all properties of an instance. Making them static would mean all instances share the exact same value, which is almost always a bug.

ONE CANONICAL EXAMPLE A simple logger class might use static members to provide a global access point without requiring instantiation. You could have a class like AppLogger with a static method log(String message). You can then call AppLogger.log('User logged in') from anywhere in your app to record an event to a single, shared list of logs.

Read the original → dart.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.