Summary - Variables
- Dart course
- Beginner
- Lesson 12/116
- 5 min
Combine var, final, const and null safety to write a profile program.
Summary - Variables
In this group you learned five ways to declare variables in Dart: var (type inference), final (runtime constant), const (compile-time constant), late (deferred init) and nullable types (?).
Combining them you can write a real profile program. We will practice with two small tasks.
In later lessons we will use these keywords for function parameters, class fields and collections too. The foundation is laid here.
Practice Profile program
Inside void main() declare three variables: var name = 'Alex', final age = 25, const city = 'London'. Then print with print('$name $age $city').
Starter code
// Declare three variables and print themSample solution
void main() {
var name = 'Alex';
final age = 25;
const city = 'London';
print('$name $age $city');
}Expected output
Alex 25 London
Practice Final profile
Inside void main() declare final name = 'Zoe' and const birthYear = 1995. Print with print('$name $birthYear').
Starter code
// Write a profile with final and constSample solution
void main() {
final name = 'Zoe';
const birthYear = 1995;
print('$name $birthYear');
}Expected output
Zoe 1995
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a compile-time constant?
- var
- final
- const Correct answer
- late
Explanation: const is set at compile time.
2 Nullable email
String? email = ____;
String? email = null;
Explanation: email can be null right now.
3 All variable concepts
| Term | Meaning |
|---|---|
var |
Type inference |
final |
Immutable |
const |
Compile-time |
String? |
Nullable |