diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_cascade.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_cascade.dart index 2304034d8835..df02ecce8800 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_cascade.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_cascade.dart @@ -30,8 +30,20 @@ class ConvertToCascade extends ResolvedCorrectionProducer { if (block is! Block) return; var previous = _getPrevious(block, node); - if (previous is! ExpressionStatement) return; - var previousOperator = _getTargetAndOperator(previous.expression)?.operator; + Token? previousOperator; + Token? semicolon; + if (previous is ExpressionStatement) { + semicolon = previous.semicolon; + previousOperator = _getTargetAndOperator(previous.expression)?.operator; + } else if (previous is VariableDeclarationStatement) { + // Single variable declaration. + if (previous.variables.variables.length != 1) { + return; + } + semicolon = previous.endToken; + } else { + return; + } var expression = node.expression; var target = _getTargetAndOperator(expression)?.target; @@ -43,7 +55,9 @@ class ConvertToCascade extends ResolvedCorrectionProducer { if (previousOperator != null) { builder.addSimpleInsertion(previousOperator.offset, '.'); } - builder.addDeletion(range.token(previous.semicolon!)); + if (semicolon != null) { + builder.addDeletion(range.token(semicolon)); + } builder.addSimpleReplacement(range.node(target), targetReplacement); }); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/convert_to_cascade_test.dart b/pkg/analysis_server/test/src/services/correction/fix/convert_to_cascade_test.dart index 66c1a2a2e40d..02749a4e5f62 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/convert_to_cascade_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/convert_to_cascade_test.dart @@ -50,6 +50,27 @@ void f(A a) { '''); } + Future test_declaration_method() async { + await resolveTestCode(''' +class A { + void m() {} +} +void f() { + final a = A(); + a.m(); +} +'''); + await assertHasFix(''' +class A { + void m() {} +} +void f() { + final a = A() + ..m(); +} +'''); + } + Future test_method_method() async { await resolveTestCode(''' class A { @@ -96,6 +117,32 @@ void f(A a) { '''); } + Future test_multipleDeclaration_first_method() async { + await resolveTestCode(''' +class A { + void m() {} +} +void f() { + final a = A(), a2 = A(); + a.m(); +} +'''); + await assertNoFix(); + } + + Future test_multipleDeclaration_last_method() async { + await resolveTestCode(''' +class A { + void m() {} +} +void f() { + final a = A(), a2 = A(); + a2.m(); +} +'''); + await assertNoFix(); + } + Future test_property_cascade() async { await resolveTestCode(''' class A {