CodeBlanks Logo Icon CodeBlanks

const constructor

Learn how const constructor improves performance.

const constructor

Marking a constructor const lets Flutter merge all instances created with the same parameters into a single canonical object. This reduces memory use and speeds up widget tree comparison. Using const where possible is a core Flutter performance tip.

class Etiket extends StatelessWidget {
  final String metin;
  const Etiket({super.key, required this.metin});

  @override
  Widget build(BuildContext context) {
    return Text(metin);
  }
}

// Usage:
Etiket(metin: 'Selam')     // new object every time
const Etiket(metin: 'Selam') // single object, reused

Canonical instance

Objects produced with const are canonical: all instances made with the same values live at the same memory address. When comparing the widget tree, Flutter can tell whether two const widgets are identical with a single address comparison. This greatly speeds up the diff algorithm.

// non-const widget: each is a new object
Text('a')
Text('a')
// const widget: single object
const Text('a')
const Text('a')

Practice Print const info

In main, print two lines with print: const tek nesne and canonical hizli.

Starter code

main.dart
void main() {
  // iki satır yazdır:
  // const tek nesne
  // canonical hizli

}

Sample solution

main.dart
void main() {
  print('const tek nesne');
  print('canonical hizli');
}

Expected output

const tek nesne
canonical hizli

Questions and answers

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

1 What does a const constructor provide?

  • Produces a new object each time
  • Produces a single canonical object for same params Correct answer
  • Allows changing parameters at runtime
  • Makes the widget invisible

Explanation: A const constructor merges all instances made with the same params into a single canonical object.

2 const constructor call

Question
final etiket = ____ Etiket(metin: 'Selam');
Answer
final etiket = const Etiket(metin: 'Selam');

Explanation: A constructor called with const produces a compile-time constant.

3 const constructor concepts

Term Meaning
const Produces a compile-time constant
canonical Single instance of the same object
performance Less memory, faster diff
const Etiket(...) Single object, reused

All lessons in Beginner