`Var A =0 ;` on pressing the button can we change `A=“name”;`?
Answer
Answer
No —
text
var A = 0text
Atext
inttext
A = "name"Why It Fails
dartvar A = 0; // Dart infers: int A = 0 // ❌ Compile-time error A = "name"; // Error: A value of type 'String' can't be assigned to a variable of type 'int'
— type is inferred at declaration and fixed from that point on.textvar
How var Type Inference Works
dartvar x = 0; // → int x = 0 var y = 3.14; // → double y = 3.14 var z = 'hello'; // → String z = 'hello' var w = true; // → bool w = true // Equivalent to explicit types: int x = 0;
If You Need to Change Type — Use dynamic
dartdynamic A = 0; A = "name"; // ✅ Works — dynamic skips type checking A = true; // ✅ Works
Comparison
| Declaration | Type | Can reassign different type? |
|---|---|---|
text | text | ❌ No |
text | text | ❌ No |
text | text | ✅ Yes |
text | text | ✅ Yes (non-null) |
Answer: No —
locks the type at inference. Usetextvarif you truly need a variable that can hold different types, though this is generally discouraged as it removes compile-time safety.textdynamic