CodeBlanks Logo Icon CodeBlanks

var and type

Learn to declare variables with var and explicit types.

var and explicit type

In Dart you declare a variable in two ways: with the var keyword or with an explicit type. For example var age = 25; and int age = 25; do the same thing.

When you use var, Dart infers the type from the value on the right. So var x = 5; makes x an int, not dynamic.

Writing the explicit type can make code more readable; in team work seeing the type helps. Both are valid; be consistent.

Type inference

Type inference means the compiler finds the type for you. When you write var name = 'Alex';, Dart knows name is a String.

Once the type is set, it does not change. So var x = 5; followed by x = 'text'; is an error; x is now an int.

Writing the explicit type can be clearer in the long run. But for short scripts var is faster. Both are accepted in Dart culture.

Practice Declare four types

Inside void main(), declare one variable of each type: int, double, String and bool. Set the values to 25, 9.99, Alex and true respectively. Then print each one with print.

Starter code

main.dart
// Declare four variables and print them

Sample solution

main.dart
void main() {
  int age = 25;
  double price = 9.99;
  String name = 'Alex';
  bool active = true;
  print(age);
  print(price);
  print(name);
  print(active);
}

Expected output

25
9.99
Alex
true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When you write var x = 5;, what is the type of x?

  • dynamic
  • int Correct answer
  • var
  • object

Explanation: Dart infers int from the value 5.

2 Integer type

Question
____ age = 25;
Answer
int age = 25;

Explanation: int is the 64-bit integer type.

3 Match the types

Term Meaning
int Integer
double Floating-point
String Text
bool Boolean

All lessons in Beginner