Skip to content

Instantly share code, notes, and snippets.

@gazialankus
Last active July 28, 2022 19:25
Show Gist options
  • Save gazialankus/fc440d205d8855f5ebbc919a12eec8ea to your computer and use it in GitHub Desktop.
Save gazialankus/fc440d205d8855f5ebbc919a12eec8ea to your computer and use it in GitHub Desktop.
An unexpected limitation in Dart null safety static analysis

An unexpected limitation in Dart null safety static analysis

Created with <3 with dartpad.dev.

class C {
int a = 1;
}
Future<void> main() async {
C? c;
// Commenting this line out gets rid of the error on line 15 below.
await Future.delayed(Duration.zero).then((_) => c = C());
if (c != null) {
// Yes the above then() appears it might execute at some point in between
// the null check and the usage.
// But we're awaiting on its future so it can't. It's already done.
print(c.a); // ERROR: IDE thinks c could be null and underlines .a here.
}
final localC = c;
if (localC != null) {
print(localC.a);
}
}
// https://twitter.com/gazialankus/status/1552593761422790657?t=XuZuWgHnQfsy_bS9sQlFaA&s=19
class C {
int a = 1;
}
Future<void> main() async {
C? c;
// Commenting this line out gets rid of the error on line 15 below.
await Future.delayed(Duration.zero).then((_) => c = C());
if (c != null) {
// Yes the above then() appears it might execute at some point in between
// the null check and the usage.
// But we're awaiting on its future so it can't. It's already done.
print(c.a); // ERROR: IDE thinks c could be null and underlines .a here.
}
final localC = c;
if (localC != null) {
print(localC.a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment