![]() |
VOOZH | about |
A variable in Dart is used to store data that can be accessed and modified during program execution. Each variable has a name and a data type that defines the kind of value it can store.
Example: The following example shows how to declare and use variables of different data types in Dart.
Output
10
0.2
false
0
Geeks for Geeks
To Declare a Variable:
data_type variable_name;
To Declare Multiple Variables:
data_type variable1, variable2, variable3;
Dart supports different types of variables:
Note: Dart is a type-safe language, meaning it checks whether the stored value matches the variable's data type.
A variable declared with the dynamic keyword can store values of different data types during program execution.
Syntax:
dynamic variable_name;
Example: The following example shows how a dynamic variable can change its data type.
Output
Geeks For Geeks
3.14157
Explanation:
final and const are used to create variables whose values cannot be changed after assignment.
1. Final: A final variable can only be assigned once.
Syntax:
final variable_name;
final data_type variable_name;
Below is the implementation of final keywords in Dart Program:
Output
Geeks For Geeks
Learning Dart
Explanation:
2. Const: A const variable stores a compile-time constant value.
Syntax:
const variable_name;
const data_type variable_name;
Note: const variables must be initialized at the time of declaration.
Below is the implementation of const Keyword in Dart Program:
Output
Geeks For Geeks
1.0
Explanation:
Dart supports null safety, which means variables cannot store null unless they are explicitly declared as nullable. This helps prevent unexpected null-related errors in programs.
Example: Assigning null to a Non-Nullable Variable
Output
Error: A value of type 'Null' can't be assigned to a variable of type 'int'.
Explanation: The variable a is of type int, so it cannot store null.
To allow a variable to store null, add ? after the data type.
Output
null
Explanation: int? makes the variable nullable, so it can store both integer values and null.