Diff btw final & const
Answer
Overview
Both
text
finaltext
constfinal — Runtime Constant
text
finaldartfinal 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
constdartconst 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 | text |
|---|---|---|
| When set | Once (runtime OK) | Compile-time only |
| Value type | Any value | Must be compile-time literal |
| Collection mutability | Collection content can change | Deeply immutable |
| In class | Instance field | Class-level (static) or compile-time |
| Widget optimization | Some | ✅ 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
everywhere possible (better performance). Usetextconstwhen the value is only known at runtime (like from API, user input, DateTime).textfinal