Reading this article https://dart.dev/tools/non-promotion-reasons, after I encountered a promotion issue in this code:
class UserViewModel extends ChangeNotifier {
final UserRepository _userRepo = UserRepository();
LocationData? currentLocationValue;
Future<bool> savePosition() async {
if (currentLocationValue != null) {
return _userRepo.saveUserPositioninProfile(
currentLocation: currentLocationValue); // <- ERROR: 'currentLocationValue' refers to a property so it couldn't be promoted.
} else {
return Future.value(false);
}
}
}
Why is it a problem for Dart to promote a field value? I am doing the null check right before the usage, how could the field still be null after my check?
I've read this explanation:
Flow-based type promotion does not apply to fields because the static analysis cannot prove that the field’s value doesn’t change between the point that you check for null and the point that you use it.
But I still cannot comprehend a real example, where the value could change if the check happens right before the usage of the variable.