diff --git a/lib/src/dart3_suggestors/null_safety_prep/use_ref_init_migration.dart b/lib/src/dart3_suggestors/null_safety_prep/use_ref_init_migration.dart index df8eb400..87a84c4f 100644 --- a/lib/src/dart3_suggestors/null_safety_prep/use_ref_init_migration.dart +++ b/lib/src/dart3_suggestors/null_safety_prep/use_ref_init_migration.dart @@ -15,6 +15,7 @@ import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:codemod/codemod.dart'; +import 'package:collection/collection.dart'; /// Suggestor that finds instances of `useRef` function invocations that /// pass an argument, and replaces them with `useRefInit` to prep for @@ -24,9 +25,11 @@ import 'package:codemod/codemod.dart'; /// /// ```dart /// // Before -/// final ref = useRef(someNonNulLValue); +/// final ref1 = useRef(someNonNulLValue); +/// final ref2 = useRef(null); /// // After -/// final ref = useRefInit(someNonNulLValue); +/// final ref1 = useRefInit(someNonNulLValue); +/// final ref2 = useRef(); /// ``` class UseRefInitMigration extends RecursiveAstVisitor with AstVisitingSuggestor { @@ -44,8 +47,14 @@ class UseRefInitMigration extends RecursiveAstVisitor } if (fnName == 'useRef') { - yieldPatch('useRefInit', possibleInvocation.function.offset, - possibleInvocation.function.end); + final argument = node.arguments.singleOrNull; + if (argument is NullLiteral) { + // Remove unnecessary null argument + yieldPatch('', argument.offset, argument.end); + } else { + yieldPatch('useRefInit', possibleInvocation.function.offset, + possibleInvocation.function.end); + } } } } diff --git a/test/dart3_suggestors/null_safety_prep/use_ref_init_migration_test.dart b/test/dart3_suggestors/null_safety_prep/use_ref_init_migration_test.dart index a6ad5a0c..b4fa8552 100644 --- a/test/dart3_suggestors/null_safety_prep/use_ref_init_migration_test.dart +++ b/test/dart3_suggestors/null_safety_prep/use_ref_init_migration_test.dart @@ -104,5 +104,25 @@ void main() { '''), ); }); + + test('removes unnecessary null arguments', () async { + await testSuggestor( + expectedPatchCount: 2, + input: withOverReactImport(''' + useTestHook() { + final foo = useRef(null); + final bar = useRef(null); + return [foo, bar]; + } + '''), + expectedOutput: withOverReactImport(''' + useTestHook() { + final foo = useRef(); + final bar = useRef(); + return [foo, bar]; + } + '''), + ); + }); }); }