CodeBlanks Logo Icon CodeBlanks

dynamic

Learn the dynamic type and runtime type checking.

The dynamic type

dynamic is a flexible type that can hold any value. When you make a variable dynamic, Dart leaves type checks to runtime.

For example dynamic x = 5; then x = 'text'; is valid. Because dynamic accepts any type.

This flexibility is not risk-free: type errors only appear when the program runs. So use dynamic carefully; prefer var or explicit types when possible.

The is operator

The is operator checks what type a variable has at runtime. x is int returns true if x is an int.

It is especially used with dynamic variables; their type is not known in advance. You check with is first, then use it safely.

Example: dynamic x = 5; if (x is int) { print('integer'); }. This gives runtime type safety.

Practice dynamic and is

Declare dynamic x = 5;. Check with if (x is int) and print print('int').

Starter code

main.dart
// Use dynamic and is

Sample solution

main.dart
void main() {
  dynamic x = 5;
  if (x is int) {
    print('int');
  }
}

Expected output

int

Questions and answers

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

1 Flexible type

Question
____ x = 5;
Answer
dynamic x = 5;

Explanation: dynamic accepts every type.

2 What is the difference between dynamic and var?

  • They are exactly the same
  • dynamic is faster
  • var is safer
  • in dynamic the type can change later Correct answer

Explanation: In dynamic the type can change at runtime; in var it cannot.

3 dynamic concepts

Term Meaning
dynamic Flexible type
is Type check
var Inference
int Integer

All lessons in Beginner