CodeBlanks Logo Icon CodeBlanks

Summary - Variables

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

main.dart
// Declare three variables and print them

Sample solution

main.dart
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

main.dart
// Write a profile with final and const

Sample solution

main.dart
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

Question
String? email = ____;
Answer
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

All lessons in Beginner