Null Safety in Dart
In Dart, by default a variable can’t be assigned Null value till it is defined that the variable can store Null value in it. This to avoid cases where user assign null value in Dart.
Example:
void main() {
int a=10;
a=NULL;
print(a);
}
The above Program will return a error.
How to assign null value to variable in Dart?
To declare a variable as nullable, you append a ‘?'
to the type of the variable. The declared variable will by default store null as value and even after assigning it values of your choice you can declare it as null afterwards.
Below is the implementation to assign null value to variables:
void main() {
int? a;
a=null;
print(a);
}
Output:
null
Dart – Variables
A variable name is the name assigned to the memory location where the user stores the data and that data can be fetched when required with the help of the variable by calling its variable name. There are various types of variable that are used to store the data. The type which will be used to store data depends upon the type of data to be stored.
Syntax: To declare a variable:
type variable_name;
Syntax: To declare multiple variables of the same type:
type variable1_name, variable2_name, variable3_name, ....variableN_name;
Types of Variables
Type of the variable can be among:
- Static Variable
- Dynamic Variable
- Final or const
Conditions to Write Variable Name
Conditions to write variable names or identifiers are as follows:
- Variable names or identifiers can’t be the keyword.
- Variable names or identifiers can contain alphabets and numbers.
- Variable names or identifiers can’t contain spaces and special characters, except the underscore(_) and the dollar($) sign.
- Variable names or identifiers can’t begin with a number.
Note: Dart supports type-checking, it means that it checks whether the data type and the data that variable holds are specific to that data or not.