Dart Static Members
Class-level properties and methods
⚡ What are Static Members?
Static members in Dart belong to the class itself rather than to instances. They can be accessed without creating objects and are shared across all instances of the class.
class Counter {
static int count = 0; // Static variable
static void increment() { // Static method
count++;
}
}
// Access without creating object
Counter.increment();
print(Counter.count); // 1
Key Static Concepts
Class-Level
Belongs to class, not instances
static String className = 'MyClass';
No Object Needed
Access directly through class name
MyClass.staticMethod();
Shared
Same value across all instances
static int sharedCounter = 0;
Utility Methods
Perfect for helper functions
static double calculateArea(r) => 3.14 * r * r;
🔹 Static Variables
Static variables are shared across all instances of a class:
class Student {
String name;
static int totalStudents = 0; // Static variable
static String schoolName = 'ABC School'; // Static variable
Student(this.name) {
totalStudents++; // Increment when new student is created
}
void displayInfo() {
print('Name: $name');
print('School: $schoolName');
print('Total students: $totalStudents');
}
// Static method to get school info
static void displaySchoolInfo() {
print('School: $schoolName');
print('Total students enrolled: $totalStudents');
}
}
void main() {
// Access static variable without creating object
print('Initial count: ${Student.totalStudents}'); // Initial count: 0
// Create students
Student student1 = Student('Alice');
Student student2 = Student('Bob');
Student student3 = Student('Charlie');
// Static variable is shared and updated
print('After creating students: ${Student.totalStudents}'); // After creating students: 3
// Call static method
Student.displaySchoolInfo();
// Instance method can access static variables
student1.displayInfo();
}
Output:
Initial count: 0
After creating students: 3
School: ABC School
Total students enrolled: 3
Name: Alice
School: ABC School
Total students: 3
🔹 Static Methods
Static methods can be called without creating class instances:
class MathUtils {
// Static constants
static const double pi = 3.14159;
static const double e = 2.71828;
// Static methods for calculations
static double circleArea(double radius) {
return pi * radius * radius;
}
static double circleCircumference(double radius) {
return 2 * pi * radius;
}
static double power(double base, int exponent) {
double result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
static bool isPrime(int number) {
if (number < 2) return false;
for (int i = 2; i <= number ~/ 2; i++) {
if (number % i == 0) return false;
}
return true;
}
// Static method to display all constants
static void showConstants() {
print('Mathematical Constants:');
print('π (Pi) = $pi');
print('e (Euler\'s number) = $e');
}
}
void main() {
// Use static methods without creating objects
double radius = 5.0;
print('Circle with radius $radius:');
print('Area: ${MathUtils.circleArea(radius)}');
print('Circumference: ${MathUtils.circleCircumference(radius)}');
print('\nPower calculations:');
print('2^3 = ${MathUtils.power(2, 3)}');
print('5^2 = ${MathUtils.power(5, 2)}');
print('\nPrime number check:');
List numbers = [2, 4, 7, 9, 11];
for (int num in numbers) {
print('$num is prime: ${MathUtils.isPrime(num)}');
}
print('');
MathUtils.showConstants();
}
Output:
Circle with radius 5.0:
Area: 78.53975
Circumference: 31.4159
Power calculations:
2^3 = 8.0
5^2 = 25.0
Prime number check:
2 is prime: true
4 is prime: false
7 is prime: true
9 is prime: false
11 is prime: true
Mathematical Constants:
π (Pi) = 3.14159
e (Euler's number) = 2.71828
🔹 Static vs Instance Members
Understanding the difference between static and instance members:
class BankAccount {
// Static members (class-level)
static String bankName = 'Global Bank';
static double interestRate = 0.05;
static int totalAccounts = 0;
// Instance members (object-level)
String accountHolder;
double balance;
int accountNumber;
BankAccount(this.accountHolder, this.balance) {
totalAccounts++;
accountNumber = totalAccounts;
}
// Instance method - can access both static and instance members
void displayAccountInfo() {
print('--- Account Information ---');
print('Bank: $bankName'); // Static variable
print('Account Holder: $accountHolder'); // Instance variable
print('Account Number: $accountNumber'); // Instance variable
print('Balance: \$${balance.toStringAsFixed(2)}'); // Instance variable
print('Interest Rate: ${(interestRate * 100)}%'); // Static variable
}
// Static method - can only access static members
static void displayBankInfo() {
print('--- Bank Information ---');
print('Bank Name: $bankName');
print('Interest Rate: ${(interestRate * 100)}%');
print('Total Accounts: $totalAccounts');
// print('Balance: $balance'); // ERROR! Cannot access instance variable
}
// Instance method
void deposit(double amount) {
balance += amount;
print('Deposited \$${amount.toStringAsFixed(2)}. New balance: \$${balance.toStringAsFixed(2)}');
}
// Static method to change interest rate for all accounts
static void updateInterestRate(double newRate) {
interestRate = newRate;
print('Interest rate updated to ${(newRate * 100)}% for all accounts');
}
}
void main() {
// Access static members without creating objects
print('Bank: ${BankAccount.bankName}');
print('Current interest rate: ${(BankAccount.interestRate * 100)}%');
// Create account objects
BankAccount account1 = BankAccount('Alice', 1000.0);
BankAccount account2 = BankAccount('Bob', 1500.0);
// Display bank info (static method)
BankAccount.displayBankInfo();
print('');
// Display individual account info (instance method)
account1.displayAccountInfo();
print('');
// Update interest rate for all accounts (static method)
BankAccount.updateInterestRate(0.06);
// Both accounts now have the new interest rate
account2.displayAccountInfo();
}
Output:
Bank: Global Bank
Current interest rate: 5.0%
--- Bank Information ---
Bank Name: Global Bank
Interest Rate: 5.0%
Total Accounts: 2
--- Account Information ---
Bank: Global Bank
Account Holder: Alice
Account Number: 1
Balance: $1000.00
Interest Rate: 5.0%
Interest rate updated to 6.0% for all accounts
--- Account Information ---
Bank: Global Bank
Account Holder: Bob
Account Number: 2
Balance: $1500.00
Interest Rate: 6.0%