Mastering “static” in Flutter and Dart

yetesfa alemayehu
4 min readJun 21, 2023

--

In Dart, “static” is a keyword that can be used to define class members (variables and methods) that belong to the class itself rather than to instances of the class. Here are some key points about using “static” in Flutter and Dart:

Photo by Austin Chan on Unsplash
  1. Static Variables:
    Static variables are declared using the “static” keyword within a class. They are shared among all instances of the class. Static variables are initialized only once and retain their values across multiple instances. They can be accessed using the class name itself, without creating an instance.
class Circle {
static double pi = 3.14;
static int maxRadius = 10;

double radius;

Circle(this.radius);

double calculateArea() {
return pi * radius * radius;
}
}
void main() {
Circle circle1 = Circle(5);
Circle circle2 = Circle(7);

print(Circle.pi); // Accessing static variable using class name
print(Circle.maxRadius); // Accessing another static variable

print(circle1.calculateArea()); // Accessing instance method
print(circle2.calculateArea());
}

In the example above, the `Circle` class has two static variables: `pi` and `maxRadius`. These variables are shared among all instances of the class. The static variables can be accessed using the class name, as shown in the `main` function.

2. Static Methods:
Static methods belong to the class itself, rather than the instances of the class. They can be called without creating an instance of the class. Static methods are useful for performing operations or computations that are not specific to any particular instance.

class MathUtils {
static int multiply(int a, int b) {
return a * b;
}

static int addAll(List<int> numbers) {
int sum = 0;
for (int number in numbers) {
sum += number;
}
return sum;
}
}
void main() {
print(MathUtils.multiply(5, 10)); // Calling static method without creating an instance

List<int> numbers = [1, 2, 3, 4, 5];
print(MathUtils.addAll(numbers));
}

In the above example, the `MathUtils` class has two static methods: `multiply` and `addAll`. These methods can be called using the class name without creating an instance of the class.

3. Utility Classes:
Utility classes are classes that provide helper functions or constants that can be accessed globally without the need for creating instances. They often have private constructors to prevent instantiation.

class StringUtils {
StringUtils._(); // Private constructor to prevent instantiation

static bool isEmpty(String text) {
return text == null || text.isEmpty;
}

static String capitalize(String text) {
if (isEmpty(text)) {
return '';
}
return text[0].toUpperCase() + text.substring(1);
}
}
void main() {
print(StringUtils.isEmpty('Hello')); // Calling static method

print(StringUtils.capitalize('world')); // Calling another static method
}

In the example above, the `StringUtils` class is a utility class with static methods like `isEmpty` and `capitalize`. The private constructor `_()` ensures that the class cannot be instantiated.

4. Sharing Data:
Static variables can be used to share data between different parts of an application, such as screens or widgets. They provide a convenient way to store and access data that needs to be shared without passing it through constructors or function parameters.

class UserPreferences {
static String username;
static bool darkModeEnabled;
}
void main() {
UserPreferences.username = 'JohnDoe'; // Setting static variable value
UserPreferences.darkModeEnabled = true;

print(UserPreferences.username);
// Accessing static variable
print(UserPreferences.darkModeEnabled);
}

In the above example, the `UserPreferences` class has static variables `username` and `darkModeEnabled`. These variables can be accessed and modified from different parts of the code without the need for complex data passing mechanisms.

5. Performance Considerations:
While static variables and methods can be beneficial in certain scenarios, their excessive use can lead to tight coupling and make code harder to maintain and test. Additionally, static methods cannot be overridden in subclasses, which may limit flexibility in some cases. It’s important to use static members judiciously.

Example:
Consider a scenario where a large number of classes use a static variable from another class. This can create tight coupling and make it challenging to modify or refactor the codebase.

To mitigate this issue, it’s recommended to evaluate whether using dependency injection or other design patterns could provide a more flexible and maintainable solution.

6. Class-level State:
Static variables can be used to maintain class-level state, meaning that the variable retains its value across multiple instances of the class. This can be useful when you want to keep track of information that is relevant to the entire class rather than individual instances.

class Counter {
static int count = 0;

Counter() {
count++;
}
}
void main() {
Counter c1 = Counter();
Counter c2 = Counter();

print(Counter.count); // Accessing static variable
}

In the above example, the `Counter` class has a static variable `count`. Each time an instance of `Counter` is created, the `count` is incremented. The static variable retains its value across multiple instances.

7. Initialization Order:
Static variables are initialized before any instance of the class is created. This means that you can access and use static variables even without creating an instance of the class.

class MyClass {
static int x = 10;

MyClass() {
print(x); // Accessing static variable during object initialization
}
}
void main() {
print(MyClass.x); // Accessing static variable without creating an instance
MyClass();
}

In the above example, the static variable `x` is initialized before any instance of the `MyClass` is created. You can access the static variable `x` without creating an instance of the class.

Summary:

When deciding whether to use static members, consider the specific requirements of your application, the need for data sharing, and the overall design and architecture of your code. It’s good practice to limit the use of static members to situations where they provide clear benefits and improve code readability and organization.

--

--

No responses yet