Let's get started with our first Dart project. We will start from a blank canvas:
- Open main.dart and delete everything. At this point, the file should be completely empty. Now, let's add the main function, which is the entry point for every Dart program:
main() {
variablePlayground();
}
- This code won't compile yet because we haven't defined that variablePlayground function. This function will be a hub for all the different examples in this recipe:
void variablePlayground() {
basicTypes();
untypedVariables();
typeInterpolation();
immutableVariables();
}
We added the void keyword in front of this function, which is the same as saying that this function returns nothing.
- Now, let's implement the first example. In this method, all these variables are mutable; they can change once they've been defined:
void basicTypes() {
int four = 4;
double pi = 3.14;
num someNumber = 24601;
bool yes = true;
bool no = false;
int nothing;
print(four);
print(pi);
print(someNumber);
print(yes);
print(no);
print(nothing == null);
}
The syntax for declaring a mutable variable should look very similar to other programming languages. First, you declare the type and then the name of the variable. You can optionally supply a value for the variable after the assignment operator. If you don't supply a value, that variable will be set to null.
- Dart has a special type called dynamic, which is a sort of "get out of jail free" card from the type system. You can annotate your variables with this keyword to imply that the variable can be anything. It is useful in some cases, but for the most part, it should be avoided:
void untypedVariables() {
dynamic something = 14.2;
print(something.runtimeType); //outputs 'double'
}
- Dart can also infer types with the var keyword. var is not the same as dynamic. Once a value has been assigned to the variable, Dart will remember the type and it cannot be changed later. The values, however, are still mutable:
void typeInterpolation() {
var anInteger = 15;
var aDouble = 27.6;
var aBoolean = false;
print(anInteger.runtimeType);
print(anInteger);
print(aDouble.runtimeType);
print(aDouble);
print(aBoolean.runtimeType);
print(aBoolean);
}
- Finally, we have our immutable variables. Dart has two keywords that can be used to indicate immutability – final and const.
The main difference between final and const is that const must be determined at compile time; for example, you cannot have const containing DateTime.now() since the current date and time can only be determined at runtime, not at compile time. See the How it works... section of this recipe for more details.
- Add the following function to the main.dart file:
void immutableVariables() {
final int immutableInteger = 5;
final double immutableDouble = 0.015;
// Type annotation is optional
final interpolatedInteger = 10;
final interpolatedDouble = 72.8;
print(interpolatedInteger);
print(interpolatedDouble);
const aFullySealedVariable = true;
print(aFullySealedVariable);
}