On this page10 sections
Lecture 036: Static Variables & Methods
| Day | 12: Singleton, Getters & Static |
| Lecture | 036 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
Each student has their own name. But "how many students have been created?" or "the school's name" belongs to students as a group, not to any one of them.
staticputs a variable or method on the class itself, shared by every object.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 030–035 (classes, constructors, getters and setters).
Learning Objectives
- Explain the difference between instance and static members
- Declare and use a static variable
- Use
static constfor fixed values that belong to a class - Write and call static methods
- Know what a static method can't do
1. Instance vs Static
| Instance member | Static member | |
|---|---|---|
| Belongs to | each object (its own copy) | the class (one shared copy) |
| Accessed with | object.name | ClassName.name |
| Example | a student's name | the number of students created |
2. Static Variables
class Student {
static int count = 0;
static const String school = 'City Public School';
String name;
Student(this.name) {
count++; // every new student increases the shared count
}
static void printCount() {
print('Students created: $count');
}
void introduce() {
print('I am $name from $school');
}
}
void main() {
print(Student.count); // 0, before any object exists
var a = Student('Ali');
var b = Student('Sara');
a.introduce();
b.introduce();
Student.printCount();
print(Student.school);
}Output
0
I am Ali from City Public School
I am Sara from City Public School
Students created: 2
City Public School- There is one
countfor the whole class. Each constructor call adds to the same counter. - A static variable exists even before any object is created.
- Instance methods (like
introduce) can use static members directly.
static const is the usual way to give a class fixed values: Colors.red, Duration.zero and
double.infinity are all static members.
3. Static Methods
A static method belongs to the class, so it's called without an object. It's ideal for helper functions that only work with their arguments:
class MathHelper {
static const double pi = 3.14159;
static double circleArea(double r) => pi * r * r;
static int maxOf(int a, int b) => a > b ? a : b;
}
print(MathHelper.circleArea(2)); // 12.56636
print(MathHelper.maxOf(7, 12)); // 12You've used static methods already: int.parse(...), int.tryParse(...), List.generate(...).
A static method has no object, so there is no this, and it can't use instance fields like
name.
Code Examples
Example 1: Numbered Tickets
class Ticket {
static int _nextNumber = 1;
static int sold = 0;
static const double price = 500;
final int number;
final String holder;
Ticket(this.holder) : number = _nextNumber++ {
sold++;
}
static double get revenue => sold * price;
void show() => print('Ticket #$number for $holder');
}
void main() {
var tickets = [Ticket('Ali'), Ticket('Sara'), Ticket('Hamza')];
for (var t in tickets) {
t.show();
}
print('Sold: ${Ticket.sold}, revenue: Rs ${Ticket.revenue}');
}Output
Ticket #1 for Ali
Ticket #2 for Sara
Ticket #3 for Hamza
Sold: 3, revenue: Rs 1500.0_nextNumber is shared, so each new ticket takes the next number (_nextNumber++ uses the value,
then adds 1). number is an instance field, different for every ticket. Getters can be static
too (revenue).
Common Beginner Mistakes
1. Reaching a static member through an object
var s = Student('Ali');
print(s.count);Error: The getter 'count' isn't defined for the type 'Student'.Use the class name: Student.count.
2. Using an instance field in a static method
class Student {
String name = 'Ali';
static void show() {
print(name);
}
}Error: Undefined name 'name'.A static method isn't called on an object, so there's no name to use. Make it an instance
method, or pass the value in as a parameter.
3. Using static for per-object data: static String name; would give every student the same
name. Only make something static if it truly belongs to the whole class.
Practice Questions
- How do you read a static variable
totalin a classOrder? - If 5
Studentobjects are created, what isStudent.count? - Write a static method
isAdult(int age)in a classRulesthat returnsage >= 18. - Can a static method use
this? - Static or instance: a product's
price? The tax rate that applies to all products?
Practice Answers
Order.total5
class Rules {
static bool isAdult(int age) => age >= 18;
}- No. It doesn't run on an object.
price→ instance; the shared tax rate → static (probablystatic const).
Key Takeaways
staticmembers belong to the class, with one shared copy.- Access them with
ClassName.member, not through an object. static constholds fixed values for a class.- Static methods are helpers that need no object; they can't use
thisor instance fields. - Instance members are per object; static members are per class.