diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_for_each_to_for_loop.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_for_each_to_for_loop.dart index 610e19b67a8..349e22bbc3a 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_for_each_to_for_loop.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_for_each_to_for_loop.dart @@ -52,6 +52,9 @@ class ConvertForEachToForLoop extends CorrectionProducer { } var target = utils.getNodeText(invocation.target!); var body = argument.body; + if (body.isAsynchronous || body.isGenerator) { + return; + } if (body is BlockFunctionBody) { await builder.addDartFileEdit(file, (builder) { builder.addReplacement(range.startStart(invocation, body), (builder) { diff --git a/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart b/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart index 75125ccb953..478b67acb45 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/convert_for_each_to_for_loop_test.dart @@ -129,6 +129,39 @@ void f(List list) { '''); } + Future test_blockBody_async() async { + await resolveTestCode(''' +void f(List list) { + list.forEach((e) async { + e.length / 2; + }); +} +'''); + await assertNoFix(); + } + + Future test_blockBody_asyncStar() async { + await resolveTestCode(''' +void f(List list) { + list.forEach((e) async* { + e.length / 2; + }); +} +'''); + await assertNoFix(); + } + + Future test_blockBody_syncStar() async { + await resolveTestCode(''' +void f(List list) { + list.forEach((e) sync* { + e.length / 2; + }); +} +'''); + await assertNoFix(); + } + Future test_expressionBody() async { await resolveTestCode(''' void f(List list) { @@ -144,6 +177,39 @@ void f(List list) { '''); } + Future test_expressionBody_async() async { + await resolveTestCode(''' +void f(List list) { + list.forEach((e) async => e.substring(3, 7)); +} +'''); + await assertNoFix(); + } + + Future test_expressionBody_asyncStar() async { + await resolveTestCode(''' +void f(List list) { + list.forEach((e) async* => e.substring(3, 7)); +} +'''); + await assertNoFix( + errorFilter: (error) => + error.errorCode.name == + LintNames.avoid_function_literals_in_foreach_calls); + } + + Future test_expressionBody_syncStar() async { + await resolveTestCode(''' +void f(List list) { + list.forEach((e) sync* => e.substring(3, 7)); +} +'''); + await assertNoFix( + errorFilter: (error) => + error.errorCode.name == + LintNames.avoid_function_literals_in_foreach_calls); + } + Future test_return() async { await resolveTestCode(''' void f(List list) {