var, final, and const in DartvarDefinition: A var variable is mutable (can change) and its type is inferred automatically.
var name = 'Rakesh';
name = 'Amit'; // ✅ allowed
finalDefinition: final variables are assigned only once. The value is determined at runtime and can't be changed later.
final city = 'Delhi';
city = 'Mumbai'; // ❌ Error: Final variable can't be reassigned
final when the value won’t change and is known only at runtime.constDefinition: const variables are compile-time constants. Their values must be known and fixed when the code is compiled.
const country = 'India';
country = 'Nepal'; // ❌ Error: Const variable can't be reassigned
const when the value never changes and is known at compile time.final and const| Aspect | final |
const |
|---|---|---|
| Mutability | Immutable (can’t change after assigning) | Immutable (must be constant from start) |
| Evaluated | At runtime | At compile-time |
| Use Case | Value known only at runtime | Value known at compile time |
| Example | final today = DateTime.now(); |
const pi = 3.14; |
void main() {
final timestamp = DateTime.now(); // ✅ valid
// const timestamp = DateTime.now(); ❌ invalid - not compile-time constant
const appName = 'MyApp'; // ✅ valid
print(timestamp);
print(appName);
}