Question #3MediumDart BasicsImportant

Diff btw var vs dynamic

Answer

Overview

Both

text
var
and
text
dynamic
declare variables without explicitly stating the type, but they behave very differently with respect to type safety.


var — Type Inferred at Compile Time

text
var
lets Dart infer the type from the assigned value. Once inferred, the type is fixed.

dart
var name = 'Alice';     // Inferred as String
var age = 28;           // Inferred as int
var price = 9.99;       // Inferred as double

// ❌ Cannot change type after inference
name = 'Bob';     // ✅ Still String — OK
// name = 42;     // ❌ Compile error — String expected

// var with no initial value → dynamic type
var x;            // Becomes dynamic
x = 42;
x = 'hello';     // ✅ No error (was dynamic)

dynamic — No Type Checking

text
dynamic
disables Dart's type checking entirely. The type is checked at runtime (not compile time).

dart
dynamic anything = 42;
anything = 'now a string'; // ✅ No error
anything = true;            // ✅ No error
anything = [1, 2, 3];      // ✅ No error

// No compile-time checking
dynamic value = 'hello';
print(value.nonExistentMethod()); // ❌ Runtime error (not caught at compile!)

Key Differences

Feature
text
var
text
dynamic
TypeInferred, then fixedChanges at runtime
Type-safe✅ Yes❌ No
Can change type❌ No (after inference)✅ Yes
Error detectionCompile-timeRuntime
IDE autocomplete✅ Works⚠️ Limited
PerformanceBetterSlower (runtime checks)

When to Use Which

dart
// ✅ Use var for local variables where type is obvious
var users = <User>[];
var response = await http.get(url);

// ✅ Use dynamic only when you truly don't know the type
dynamic jsonValue = jsonDecode(response.body); // Could be Map or List
void serialize(dynamic obj) { ... } // Accepts unknown types

// ✅ Even better — use explicit types or generics over dynamic
Map<String, dynamic> json = jsonDecode(body); // Better — Map with dynamic values

Comparison with Other Keywords

dart
var name = 'Alice';       // Inferred = String, type-safe
dynamic name = 'Alice';   // No type checking
String name = 'Alice';    // Explicit — most clear
Object name = 'Alice';    // Any non-null Dart object
Object? name = null;      // Any object or null

Best Practice: Use

text
var
for local variables (type is obvious from context). Avoid
text
dynamic
— use proper types, generics, or
text
Object?
when you need flexibility.
text
dynamic
removes Dart's compile-time safety net.