diff --git a/lib/src/rules/prefer_void_to_null.dart b/lib/src/rules/prefer_void_to_null.dart index 9a4267c92..8712a1aec 100644 --- a/lib/src/rules/prefer_void_to_null.dart +++ b/lib/src/rules/prefer_void_to_null.dart @@ -140,6 +140,13 @@ class _Visitor extends SimpleAstVisitor { return; } + if (parent is VariableDeclarationList && + node == parent.type && + parent.parent is! FieldDeclaration) { + // We should not recommend to use `void` for local or top-level variables. + return; + } + // [] or {} if (parent is TypeArgumentList) { var literal = parent.parent; diff --git a/test/rules/prefer_void_to_null_test.dart b/test/rules/prefer_void_to_null_test.dart index 9df96ae35..a4f5234e8 100644 --- a/test/rules/prefer_void_to_null_test.dart +++ b/test/rules/prefer_void_to_null_test.dart @@ -35,6 +35,20 @@ void f(int a) { case var _ as Null: } } +'''); + } + + test_localVariable() async { + await assertNoDiagnostics(r''' +void f() { + Null _; +} +'''); + } + + test_topLevelVariable() async { + await assertNoDiagnostics(r''' +Null a; '''); } } diff --git a/test_data/rules/prefer_void_to_null.dart b/test_data/rules/prefer_void_to_null.dart index a3cebabf9..1de5b25c5 100644 --- a/test_data/rules/prefer_void_to_null.dart +++ b/test_data/rules/prefer_void_to_null.dart @@ -52,8 +52,6 @@ class F implements E { } void void_; // OK -Null null_; // LINT -core.Null core_null; // LINT Future? future_void; // OK Future? future_null; // LINT Future? future_core_null; // LINT @@ -72,8 +70,6 @@ void Function(Future)? voidFunctionFutureNull; // LINT usage() { void void_; // OK - Null null_; // LINT - core.Null core_null; // LINT Future? future_void; // OK Future future_null; // LINT Future future_core_null; // LINT @@ -152,8 +148,6 @@ class AsMembers { void usage() { void void_; // OK - Null null_; // LINT - core.Null core_null; // LINT Future? future_void; // OK Future future_null; // LINT Future future_core_null; // LINT