Understanding Variables in Dart: static, const, var, dynamic, late and final
Learn the differences between static, const, var, dynamic, late and final variables, and how they impact your code.
Dive into the world of variables in Dart!
Explore real-time examples to grasp these concepts effectively.
..
Variables are placeholders that store data in memory during program execution.
Dart allows you to declare variables with various modifiers to control their behavior. Let's take a closer look at the commonly used modifiers:
static
static is used to declare class-level variables and methods that belong to the class itself, rather than to instances of the class.
These variables are accessible without creating an instance of the class.
Example:
class MathUtils {
static const double pi = 3.14159;
static int add(int a, int b) {
return a + b;
}
}
..
final
final is used for declaring variables with fixed values that cannot be reassigned after initialization.
It must be initialized during declaration.
Example:
void main() {
final int numberOfDays = 7;
final double taxRate = 0.08;
}
..
const
const is used to define compile-time constants that must be initialized with a constant value.
It is immutable during runtime, meaning its value cannot be changed.
Example:
void main() {
const double gravity = 9.81;
const int secondsInMinute = 60;
}
..
var
var is used to declare variables with inferred data types. The type is determined based on the value assigned during initialization.
Once the type is inferred during compilation, it cannot be changed.
Example:
void main() {
var age = 30; // The compiler infers that 'age' is of type 'int'.
var name = "John Doe"; // The compiler infers that 'name' is of type 'String'.
}
..
dynamic
dynamic is used for declaring variables with dynamic data types. The type can be changed at runtime.
It provides flexibility but reduces static type checking.
Example:
void main() {
dynamic dynamicVariable = 42; // 'dynamicVariable' is initially of type 'int'.
dynamicVariable = "Hello"; // The type of 'dynamicVariable' changes to 'String'.
}
..
late
late is used for non-nullable variables that are guaranteed to be initialized before they are used, even if not initialized during declaration.
Unlike final, late variables are not required to be initialized immediately.
void main() {
late int lateVariable;
lateVariable = 42; // 'lateVariable' is initialized later before use.
print("Late Variable: $lateVariable"); // Output: Late Variable: 42
}
..
Comments
Post a Comment