Skip to content

[linter request] Don't use a non-nullable casting type when combined with conditional member accessΒ #59805

@Reprevise

Description

@Reprevise

Dart should have a lint to ensure that users who combine conditional access and casting that the casting type is nullable. An alternative solution would be to have the user switch to using the bang (!) operator instead to show intent.

BAD:

bool? getBool(List<List<Object>?> input) {
  return input.firstOrNull?.single as bool; // Non-null type combined with conditional access, will throw a TypeError
}

void main() {
  final objects = <List<Object>?>[null, ["bar"], [2]];
  getBool(objects);
}

GOOD:

bool? getBool(List<List<Object>?> input) {
  return input.firstOrNull?.single as bool?; // Nullable type combined with conditional access, no TypeError
}

bool? getBool(List<List<Object>?> input) {
  return input.firstOrNull!.single as bool; // Using a bang operator instead
}

void main() {
  final objects = <List<Object>?>[null, ["bar"], [2]];
  getBool(objects);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    P4area-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-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions