Fixing `Module was compiled with an incompatible version of Kotlin.`

Today I upgraded Flutter from version 2.7 to 2.9, and my app compilation started failing with this error:

~/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.5.31/43331609c7de811fed085e0dfd150874b157c32/kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

A quick search led me to this post on StackOverflow. It looks like I have to update the version in my android/build.gradle file:

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
...

I wonder how that kotlin-stdlib got updated though. Was it because I upgraded Flutter? So I changed the version t0 1.5.1 to match the version listed in the error message but got this:

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.1.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.1/kotlin-gradle-plugin-1.5.1.pom
       - https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.1/kotlin-gradle-plugin-1.5.1.jar
       - https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.1/kotlin-gradle-plugin-1.5.1.pom
       - https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.5.1/kotlin-gradle-plugin-1.5.1.jar
     Required by:
         project :

Looks like I had misread the error message earlier. I should have used version 1.5.31. After switching to this version and compiling, I am making some progress but get another error message:

* Where:
Build file '/Users/anhtuan/git/trading_journal/android/app/build.gradle' line: 25

* What went wrong:
A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'kotlin-android']
   > The current Gradle version 5.6.2 is not compatible with the Kotlin Gradle plugin. Please use Gradle 6.1.1 or newer, or the previous version of the Kotlin plugin.

I've done something like that before! Looking back at http://blog.wafrat.com/flutter-androidx-migration/, all I have to do is open android/gradle/wrapper/gradle-wrapper.properties and set the version there:

After I changed the Gradle version, the app finally compiled.