Question #4MediumGeneralArchitecture

If `int? A =0;` can I make it as null on pressing the button?

Answer

Answer

Yes! If a variable is declared as nullable (

text
int? A = 0
), you can set it to
text
null
at any time.


Example

dart
int? A = 0; // Nullable int — can hold int OR null

// On button press
ElevatedButton(
  onPressed: () {
    setState(() {
      A = null; // ✅ Perfectly valid — nullable type allows null
    });
  },
  child: Text('Make Null'),
)

// Check after
print(A); // null
print(A == null); // true

Key Concept: Nullable vs Non-Nullable

dart
int  A = 0;  // Non-nullable — CANNOT be null
int? A = 0;  // Nullable — CAN be null (? makes it nullable)

// Non-nullable — compile error
int B = 0;
B = null; // ❌ Error: Null can't be assigned to int

// Nullable — works fine
int? C = 0;
C = null; // ✅ No error

Null Safety in Dart

Dart has sound null safety (since Dart 2.12). Every type is non-nullable by default. Adding

text
?
explicitly opts into nullable.

dart
int?  a = null;     // ✅ Nullable
String? b = null;   // ✅ Nullable
double? c = null;   // ✅ Nullable

// Access null-safely
print(a ?? 0);        // 0 (default if null)
print(a?.toString()); // null (safe call)

Answer: Yes —

text
int? A = 0
can be set to
text
null
because the
text
?
makes it a nullable type. Non-nullable
text
int A = 0
cannot be set to
text
null
.