Skip to content

Conditionals and "cast_nullable_to_non_nullable" #60055

@RohitSaily

Description

@RohitSaily

Dart SDK version: 3.8.0-24.0.dev (dev) (Wed Jan 22 12:05:43 2025 -0800) on "macos_x64"

Details for cast_nullable_to_non_nullable indicate the intention of the rule is to not have implicit casting from a nullable type to one that is not nullable. Shouldn't this also apply to conditional checks? This aligns with its stated motivation

DON'T cast a nullable value to a non nullable type. This hides a null check and most of the time it is not what is expected.

The rest of this post shows multiple ways the nullability can be made more explicit, although for simplicity, standard style(s) may need to be selected. Also, making the nullability more explicit does result in slightly more code, but that seems to be the point of the rule.

Case Patterns

BAD

void function(final Object? object)
{	if (object case final String s)
		{}
}

GOOD
Something that directly indicates the value was nullable.

void function(final Object? object)
{	if (object case final String s?)
		{}
}
void function(final Object? object)
{	if (object! case final String s)
		{}
}
void function(final Object? object)
{	if (object case final String? s when s!=null)
		{}
}

Type Checks

BAD

void function(final Object? object)
{	if (object is String)
		{}
}

GOOD
Again, something that directly indicates the value was nullable.

void function(final Object? object)
{	if (object!=null&&(object is String))
		{}
}
void function(final Object? object)
{	if ((object is String?)&&object!=null)
		{}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-linterIssues with the analyzer's support for the linter packagetype-uxA user experience or user interface related issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions