From 57da93ad4f2b1479245238e77ffbd52315ca841c Mon Sep 17 00:00:00 2001 From: Sam Rawlins Date: Wed, 13 May 2026 07:03:42 -0700 Subject: [PATCH] linter: collection_methods_unrelated_type: Null not related to non-nullable Fixes https://github.com/dart-lang/sdk/issues/57101 This change affects collection_methods_unrelated_type and unrelated_type_equality_checks. For example these are now reported: ```dart void f(Set p1, int p2) { p1.contains(null); p2 == null; } ``` Change-Id: Ib58bad2beb6b9df8fe7c71f27213055e9b8d5cb9 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/489481 Reviewed-by: Brian Wilkerson Commit-Queue: Samuel Rawlins --- .../lib/src/util/dart_type_utilities.dart | 6 ++++ ...ollection_methods_unrelated_type_test.dart | 33 ++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/pkg/linter/lib/src/util/dart_type_utilities.dart b/pkg/linter/lib/src/util/dart_type_utilities.dart index 1d8b43a4b2c..583f37ef7e7 100644 --- a/pkg/linter/lib/src/util/dart_type_utilities.dart +++ b/pkg/linter/lib/src/util/dart_type_utilities.dart @@ -182,6 +182,12 @@ bool typesAreUnrelated( } var promotedLeftType = typeSystem.promoteToNonNull(leftType); var promotedRightType = typeSystem.promoteToNonNull(rightType); + if (leftType.isDartCoreNull && typeSystem.isNonNullable(rightType)) { + return true; + } + if (rightType.isDartCoreNull && typeSystem.isNonNullable(leftType)) { + return true; + } if (promotedLeftType == promotedRightType || typeSystem.isSubtypeOf(promotedLeftType, promotedRightType) || typeSystem.isSubtypeOf(promotedRightType, promotedLeftType)) { diff --git a/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart b/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart index dc9cecfaceb..42426078260 100644 --- a/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart +++ b/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart @@ -65,7 +65,23 @@ var x = [].contains(C()); } test_contains_related_null() async { - await assertNoDiagnostics('var x = [].contains(null);'); + await assertNoDiagnostics('var x = [].contains(null);'); + } + + test_contains_related_null_genericNullable() async { + await assertNoDiagnostics(''' +bool f() { + return [].contains(null); +} +'''); + } + + test_contains_related_null_genericNullable2() async { + await assertNoDiagnostics(''' +bool f() { + return [].contains(null); +} +'''); } test_contains_related_Object() async { @@ -164,6 +180,21 @@ abstract class C implements List { ); } + test_contains_unrelated_null() async { + await assertDiagnostics('var x = [].contains(null);', [lint(25, 4)]); + } + + test_contains_unrelated_null_generic() async { + await assertDiagnostics( + ''' +bool f() { + return [].contains(null); +} +''', + [lint(53, 4)], + ); + } + test_contains_unrelated_recordAndNonRecord() async { await assertDiagnostics("var x = <(int, int)>[].contains('hi');", [ lint(32, 4),