The Var Keyword
-
var
- There is no need to specify the variable's type.
- When updating the value, it must match the original type of the variable.
- Explicit Declaration
- Conventionally, the
var
keyword is used to declare local variables within functions or methods (recommended by the Dart style guide, as the compiler knows the type anyway). - When declaring variables or properties in a class, the type is specified.
- Conventionally, the
Dynamic Type
- A keyword used for variables that can have various types.
- It's not generally recommended, but it can be very useful at times.
- Why? It is used when it is difficult to know what type a variable will be, especially when working with Flutter or JSON.
- Example of usage:
void main() {
var a;
dynamic b;
}
Nullable Variables
Null safety prevents the developer from referencing null values.
In Dart, it must be clearly indicated whether a variable can be null.
void main() {
String? nico = 'nico';
nico = null;
nico?.isNotEmpty; // This checks if the value exists before proceeding with the following operations. Equivalent to the below.
if (nico != null) {
nico.isNotEmpty;
}
}
Final Variables
To define a variable that cannot be modified, use final
instead of var
.
It's similar to const
in JavaScript or TypeScript.
void main() {
final a = 'nico';
final String b = 'nico';
}
Late Variables
late
is a modifier that can be added before final
or var
.
late
allows declaring a variable without initial data.
void main() {
late final String name;
// do something, go to api
name = 'nico';
}
Constant Variables
const
in Dart is different from JavaScript or TypeScript.
In JavaScript or TypeScript, const
is similar to final
in Dart.
In Dart, const
is used to create compile-time constants.
It's used for values that are known at compile time.
These values are known before uploading the app to the app store.
void main() {
const name = 'nico';
const max_allowed_price = 120;
}
Recap
According to Dart's style guide, it is recommended to use var
as much as possible, and using types is advised when writing properties in a class. When declaring local variables within methods or small functions, using var
is preferable since the compiler will infer the variable's type anyway.
The dynamic
type must be used very cautiously.