dart-lang / dart-lang/language

`@pragma` for dart analyzer to hint null type promotion.

Open
#3,447 6 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Hi,

the following code will work perfectly fine with current Dart 3.1.3:

String? foo = null; 

if (foo != null) {
  String x = foo; // works, no ! needed
}

Now, I often want to check if the String has content, which leads to:

String? foo = null; 

if (foo != null && foo.isNotEmpty) {
  String x = foo; // works, no ! needed
}

Since I use that quite often in my app, I thought it might be nice to have an extension method for that:

extension NullableStringExtension on String? {
  bool get hasContent => this != null && this!.isNotEmpty;
}

The usage should be:

String? foo = null;

if (foo.hasContent) {
  String x = foo; // Urgh, does not work, because Dart thinks, that foo could be null.
}

However, this does not work, because the analyzer still thinks, that the foo could be null. Since hasContent already checks for that and only returns true, when foo is not null, it would be nice, if either the analyzer can actually analyze it, or it would be nice, if there was some pragma, like:

extension NullableStringExtension on String? {
  @pragma('not-null-when-true')
  bool get hasContent => this != null && this!.isNotEmpty;
}

This is similar to a C# feature: NotNullWhen.

It would be great so have something similar in Dart as well.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Dart 3.1.3 null-safety examples in the issue and review the proposed @pragma('not-null-when-true') behavior alongside the linked C# NotNullWhen reference. Done would require a language and analyzer design that lets foo be treated as non-null after hasContent evaluates true.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.