Solution to gradlew The operation couldn’t be completed. Unable to locate a Java Runtime on MacOS and Windows

- Andrés Cruz

En español

The "Unable to locate a Java Runtime" error in Flutter usually occurs when a valid Java installation is not found on the system, this error can occur in multiple scenarios and you do not necessarily have Java installed on your computer (unless you are programming in Java) if you are developing with Kotlin or Flutter, these libraries already have some package that you can reference instead, although the basic error is that the JAVA_HOME environment variable that usually references the JDK folder in Java has not been configured, although again in the Google ecosystem it was replaced by the company's own development kit.

In MacOS

This article is focused on the development of Flutter on MacOS, although you can take similar steps on any other operating system such as Windows or Linux.

In our terminal, we define the environment variable using:

export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jbr/Contents/Home

As you can see, we reference the Android Studio app, if you vary the installation of this, you must enter the path corresponding to the installation, it is important to note that the folder is not the Java one, whose installation is not necessary but a local to Android Studio JBR.

With the previous steps, you will be able to execute the gradlew command without problems. It is important to note that the previous change is not permanent and is automatically deleted when you close the terminal.

This error can also happen when the app in Flutter gets stuck or in an infinite loop at compile time.

In Windows

If you have an old installation of Flutter and Android Studio, you may get an error like the following:

ERROR: JAVA_HOME is set to an invalid directory: C:\Program Files\Android\Android Studio\jre
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
\android> JAVA_HOME="C:\Program Files\Android\Android Studio\jbr"

This is because now the folder is not jre but jbr

To update the JAVA_HOME environment variable in Windows, you must right click on Computer, then Advanced System Configuration and finally on Environment Variables in which you must enter the correct name, which would be something like:

JAVA_HOME="C:\Program Files\Android\Android Studio\jbr"
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.