Flutter

What is difference between const and final keyword in flutter

In Flutter (and Dart), both const and final are used to declare immutable variables, but there are key differences in when and how they are initialized.

Summary of Differences

Featurefinalconst
ImmutabilitySingle assignment onlySingle assignment only
When InitializedAt runtimeAt compile time
UsageWhen value is known at runtimeWhen value is known at compile time
MemoryNew instance each timeCanonicalized (same instance reused)
Can be used withAPI responses, dynamic valuesStatic values like hard-coded literals
In ClassesUse final for instance fieldsUse const for compile-time constants

Detailed Explanation

final

  • Initialized only once
  • Value is set at runtime
  • Useful when you don’t know the value until runtime (e.g., API results, user input, DateTime)
final name = 'John';
final currentTime = DateTime.now(); // Allowed

const

  • Compile-time constant
  • Must be initialized with a value known at compile time
  • Uses canonicalization – same object is reused in memory
const pi = 3.14;
const list = [1, 2, 3];

const time = DateTime.now(); //  Error: not allowed (runtime value)

const with Widgets

In Flutter UI code, you often use const for widgets to improve performance:

const Text('Hello'); // Widget is created at compile time and reused

This avoids unnecessary rebuilds and improves efficiency.


When to Use What?

Use caseKeyword to use
Value doesn’t change and known earlyconst
Value doesn’t change but known laterfinal
Value changesNo final/const

Leave a Reply

Your email address will not be published. Required fields are marked *