Cannot run project.afterevaluate(closure) when the project is already evaluated.

When encountering the error message “cannot run project.afterevaluate(closure) when the project is already evaluated,” it means that you are trying to execute a Gradle task or script after the project evaluation phase has already taken place. In Gradle, the project evaluation phase initializes the project object model and applies configuration to all projects and their tasks.

The most common cause of this error is trying to modify the project configuration or execute a task during or after the execution phase, which is too late as the project has already been evaluated. To understand this better, let’s look at an example:

        build.gradle:

        task myTask {
            doLast {
                println "Running myTask"
            }
        }

        afterEvaluate {
            myTask.doLast {
                println "This will not be executed"
            }
        }
    

In this example, we define a custom task called “myTask” and add some actions to be performed when the task is executed. Then, we use the “afterEvaluate” block to add additional actions to “myTask” after the evaluation phase. However, since the evaluation phase has already passed when the “afterEvaluate” block is executed, the additional actions will not be executed.

To fix this issue, you need to move the desired configuration or task execution logic to an appropriate phase that comes before the evaluation phase. For example, in the previous example, you could directly add the additional actions to “myTask” without the need for the “afterEvaluate” block:

        build.gradle:

        task myTask {
            doLast {
                println "Running myTask"
                // Additional actions here
            }
        }
    

By doing this, the additional actions will be executed when “myTask” is invoked, avoiding the error message.

Same cateogry post

Leave a comment