Question #23MediumDart Basics

`Var A =0 ;` on pressing the button can we change `A=“name”;`?

Answer

Answer

No

text
var A = 0
infers
text
A
as type
text
int
. You cannot reassign it with
text
A = "name"
because that would be a type mismatch.


Why It Fails

dart
var 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'

text
var
— type is inferred at declaration and fixed from that point on.


How var Type Inference Works

dart
var 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

dart
dynamic A = 0;
A = "name";  // ✅ Works — dynamic skips type checking
A = true;    // ✅ Works

Comparison

DeclarationTypeCan reassign different type?
text
var A = 0
text
int
(inferred, fixed)
❌ No
text
int A = 0
text
int
(explicit)
❌ No
text
dynamic A = 0
text
dynamic
✅ Yes
text
Object A = 0
text
Object
✅ Yes (non-null)

Answer: No —

text
var
locks the type at inference. Use
text
dynamic
if you truly need a variable that can hold different types, though this is generally discouraged as it removes compile-time safety.