Question #2MediumDart BasicsImportant

Diff btw final & const

Answer

Overview

Both

text
final
and
text
const
declare variables that can only be set once. The key difference is when the value is determined.


final — Runtime Constant

text
final
is assigned once and cannot be changed. The value can be determined at runtime.

dart
final name = 'Alice';              // Set once — cannot reassign
final DateTime now = DateTime.now(); // OK — runtime value
final list = [1, 2, 3];           // Reference is final, but list is mutable!

list.add(4);     // ✅ Works — list content can change
// list = [5];   // ❌ Error — can't reassign the reference

// In a class
class User {
  final String id;         // Must be set in constructor
  final String name;

  User(this.id, this.name);
}

const — Compile-Time Constant

text
const
must be determined at compile time — the value must be known before running.

dart
const pi = 3.14159;
const appName = 'MyApp';
const maxRetries = 3;

// const list — deeply immutable
const colors = ['red', 'green', 'blue'];
// colors.add('yellow'); // ❌ Error — const collections are immutable!

// ❌ Cannot use runtime values
// const now = DateTime.now(); // Error! Runtime value

In Widgets — const Constructors

dart
// const widget — created at compile time, cached
// Flutter reuses the same widget instance → better performance
const Text('Hello World');     // ✅ const widget
const SizedBox(height: 16);   // ✅ const widget
const Padding(padding: EdgeInsets.all(8), child: Text('Hi')),

// final inside StatelessWidget
class MyWidget extends StatelessWidget {
  final String title; // Runtime — set by parent
  const MyWidget({required this.title}); // Constructor is const
}

Key Differences

Feature
text
final
text
const
When setOnce (runtime OK)Compile-time only
Value typeAny valueMust be compile-time literal
Collection mutabilityCollection content can changeDeeply immutable
In classInstance fieldClass-level (static) or compile-time
Widget optimizationSome✅ Maximum (reused)
dart
// final can hold runtime values
final time = DateTime.now();    // ✅
final user = fetchUser();      // ✅ (Future result)

// const cannot
const time = DateTime.now();   // ❌ Compile error

Rule: Prefer

text
const
everywhere possible (better performance). Use
text
final
when the value is only known at runtime (like from API, user input, DateTime).