Understanding Static Keyword in Flutter (Dart)
The static keyword in Flutter (Dart) is used to declare class-level variables and methods. This means that the member belongs to the class itself rather than an instance of the class.
Key Features of static in Flutter (Dart)
- Class-Level Access: Static members can be accessed using the class name without creating an instance.
- Memory Optimization: Static members are stored once in memory and shared across all instances.
- Cannot Use
this: Static members do not belong to an instance, so they cannot usethis.
Usage of static in Dart
1. Static Variables
Static variables belong to the class rather than instances.
class MyClass {
static String appName = "Zamalyft";
}
void main() {
print(MyClass.appName); // Access without an instance
}
2. Static Methods
Static methods can be called without creating an instance of the class.
class Utility {
static void showMessage(String msg) {
print("Message: $msg");
}
}
void main() {
Utility.showMessage("Welcome to Flutter!");
}
3. Static Constants
Static constants are declared using static const.
class Config {
static const double pi = 3.14159;
}
void main() {
print(Config.pi);
}
4. Static with Private Variables
Static variables can also be private using an underscore (_).
class Database {
static String _connection = "Connected";
static String getConnectionStatus() {
return _connection;
}
}
void main() {
print(Database.getConnectionStatus());
}
When to Use static?
- When a variable or method should be shared across all instances of a class.
- For utility/helper functions (e.g., formatting, logging).
- For defining constants using
static const. - For implementing singleton patterns.
By using the static keyword effectively, you can optimize memory usage and organize your Flutter code efficiently!
Comments
Post a Comment