Interview frequency: …
Short answer
A non-nullable type such as String does not accept null, and when a value is optional we write String? and check it before use.
Explanation
Null safety lets the compiler catch most null errors before running. Use ? for a nullable type, and convert to a non-nullable type after a clear condition. The ! operator forces the compiler to trust you, but it throws a runtime error if the value really is null.
Code example
String? nickname;
if (nickname != null) {
print(nickname.length);
}Common mistakes
- Using ! as a permanent fix instead of checking the value or designing the type more clearly.
- Treating String? as equal to String; the former needs explicit null handling.