CodeBlanks Logo Icon CodeBlanks

const

Learn to define compile-time constants with const.

The const keyword

With const you declare a compile-time constant. The value is known before the program runs, during compilation. For example const maxScore = 100;.

const only works with constant expressions: numbers, string literals and operations on constants. Runtime-computed values like DateTime.now() cannot be const.

Because const values are computed at compile time, a single copy is kept in memory; this is a performance gain. Prefer const for values you know are fixed.

When to use const?

Typical cases for const: math constants (const pi = 3.14;), app versions (const version = '1.0.0';), fixed lists and configuration constants.

If a value must be computed at runtime (user input, time, random numbers) you cannot use const; choose final or var.

In frameworks like Flutter, writing const in front of const widgets is common; it boosts performance. We will see this later.

Practice Declare a const constant

Declare maxScore with const set to 100 and print it.

Starter code

main.dart
// Declare a const constant

Sample solution

main.dart
void main() {
  const maxScore = 100;
  print(maxScore);
}

Expected output

100

Questions and answers

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

1 Compile-time constant

Question
____ maxScore = 100;
Answer
const maxScore = 100;

Explanation: const is a compile-time constant.

2 What is the key difference between const and final?

  • final is faster
  • They are exactly the same
  • const can only be used inside a class
  • const is set at compile time, final at runtime Correct answer

Explanation: const at compile time, final at runtime.

3 const concepts

Term Meaning
const Compile-time constant
final Runtime constant
var Mutable
late Deferred init

All lessons in Beginner