Diff btw var vs dynamic
Answer
Overview
Both
text
vartext
dynamicvar — Type Inferred at Compile Time
text
vardartvar 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
dynamicdartdynamic 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 | text |
|---|---|---|
| Type | Inferred, then fixed | Changes at runtime |
| Type-safe | ✅ Yes | ❌ No |
| Can change type | ❌ No (after inference) | ✅ Yes |
| Error detection | Compile-time | Runtime |
| IDE autocomplete | ✅ Works | ⚠️ Limited |
| Performance | Better | Slower (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
dartvar 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
for local variables (type is obvious from context). Avoidtextvar— use proper types, generics, ortextdynamicwhen you need flexibility.textObject?removes Dart's compile-time safety net.textdynamic