Advertisement
Beginner Flutter, Dart Null Safety

What does the question mark symbol mean when it appears after a type in a Dart variable declaration, such as String?, and how is a nullable type actually different from a regular non nullable type?

Short answer

Adding a question mark immediately after a type name, such as writing String? instead of simply String, explicitly declares that a specific variable is allowed to hold either a genuine value of that declared type or the special value null, and the Dart compiler then requires you…

Save Flutter mock interview
Advertisement
AModel answer
Adding a question mark immediately after a type name, such as writing String? instead of simply String, explicitly declares that a specific variable is allowed to hold either a genuine value of that declared type or the special value null, and the Dart compiler then requires you to properly handle both of those two distinct possibilities anywhere that nullable variable is actually used, such as checking whether it is null before attempting to call a method on it, which is different from a regular non nullable type where the compiler already guarantees a real, usable value is always present.
String? middleName;
print(middleName?.length ?? 0);
Real-world example
A user profile form declares its optional middle name field as a nullable String, correctly reflecting that many users simply do not have a middle name to actually provide, while still requiring the app to handle that missing value safely and explicitly wherever it is later used.
Likely follow-ups
  • What is the difference between a nullable type and simply giving a variable a default empty value instead?
  • How do you convert a nullable variable into a non nullable one after confirming it is not null?
Related topics