Open
Description
Considering this code:
void main() {
Person person = new Person(
name: "Leonardo",
);
if (person.jobTitle != null) {
showInConsole(person.jobTitle); // Error: The argument type 'String?' can't be assigned to the parameter type 'String'
}
}
class Person {
final String name;
final String? jobTitle;
const Person({required this.name, this.jobTitle});
}
void showInConsole(String text) {
print(text);
}
In the error line, person.jobTitle
will not be null as it was checked for that before, but the analyzer keeps it with its original signature. Because of that, it is not usable inside the showInConsole
function.
Some workarounds?
- Using a local variable for the property. In this case, I'm not sure if the analyzer keeps the local variable with its original signature after the null check, but it doesn't show an error anymore.
String? jobTitle= person.jobTitle;
if (jobTitle != null) {
showInConsole(jobTitle); // no errors
}
- Using the
!
operator. But I'm not sure about this. Coming from TypeScript, this is a bad practice because if I remove the null check for some reason, it won't show the error and it will be throwing a runtime error.
if (person.jobTitle != null) {
showInConsole(person.jobTitle!); // no errors
}
The first workaround is the safest way, I think. But what if I change the type of cardBrand
in the future? I would need to change it in every location I check for the property to not be null. Also, it could be annoying to create a local variable for every property you need to check.
If the analyzer can follow the flow of the first workaround for a local variable so it knows it's not null, shouldn't it do the same for the property of a local variable?