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 = 0text
nullExample
dartint? 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
dartint 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
?dartint? 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 —
can be set totextint? A = 0because thetextnullmakes it a nullable type. Non-nullabletext?cannot be set totextint A = 0.textnull