dart-lang / dart-lang/language

Null-aware return doesn't promote variable

Open
#4,156 3 comments 0 reactions 0 assignees View on GitHub
request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Consider this code:

```dart
final lastTransaction = transactions.lastOrNull;
if (lastTransaction?.expirationDate == null) {
return false;
}

final expirationDate = DateTime.tryParse(lastTransaction!.expirationDate!);
```

If I remove the `!`, I get an analyser error saying I can't use `lastTransaction` because it can be `null`. I believe the analyser should be able to conclude that `lastTransaction` can't be `null`, because it's a final local variable, and the `?.` in the `if` check would ensure there's no valid code path for it to still be `null`.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the reported Dart snippet and checking the analyzer's null-safety promotion behavior after the null-aware condition. Read the language's rules for local-variable promotion and null-aware access; done means the analyzer consistently accepts using lastTransaction and expirationDate without the non-null assertions, with coverage for this example.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.