Learn to store values in typed variables, write functions, and understand the protection against null.
Open this lesson in KodokonBefore building screens, let's learn the basics of Dart, Flutter's language. A variable is a labeled box in the computer's memory, in which you store a value to reuse it later. In Dart, every variable has a type: the nature of what it can hold. The four most common types are int (a whole number, like 28), double (a decimal number, like 1.65), String (a string of characters, meaning text between quotes) and bool (a boolean: either true or false). The var keyword lets Dart figure out the type on its own from the value you provide.
void main() {
var name = "Camille";
int age = 28;
double height = 1.65;
bool isStudent = true;
print(name);
print(age);
print(height);
print(isStudent);
}print displays a value in the console, the text area where the program writes its messages: very handy for checking what's going on. To insert a variable in the middle of some text, Dart offers interpolation: place the $ symbol before the variable name, directly inside the string. Another useful keyword, final, declares a variable that can never change again after receiving its first value: use it as soon as a value isn't meant to evolve.
void main() {
final city = "Lyon";
var temperature = 21;
print("In $city, it is $temperature degrees.");
}A function is a small reusable block of code that has a name, may receive parameters (input values, in parentheses), and can return a result with the return keyword. You declare it by writing first the result's type, then its name, then its parameters. The void type means "returns nothing": that's the case with main, the program's entry point.
int add(int a, int b) {
return a + b;
}
String greet(String name) {
return "Hello, $name!";
}
void main() {
print(add(2, 3));
print(greet("Nadia"));
}One last key concept: null safety. null is a special value that means "nothing, no value". Forgotten nulls have historically been one of the leading causes of app crashes. Dart protects you: by default, a variable cannot hold null. To allow it explicitly, add a question mark to the type: String? reads as "a string of characters, or nothing". The ?? operator then provides a fallback value, used only if the variable is null.
void main() {
String? nickname;
print(nickname ?? "No nickname yet");
nickname = "Momo";
print(nickname);
}String? nickname mean?int add(int a, int b) { return a + b; }, what does print(add(2, 3)) display?