I've been facing a similar issue in my project. After sometime trying to figure out what was going on, I finally found the problem in my project.
In my case, the problem was due to the JAVA version in my machine, the JAVA version in my Android Studio setup and the JAVA version that Gradle was expecting.
In my project, the Gradle version was 7.6, so check this table provided by them the JDK version I should be using was 19. So I installed the openjdk-19-jdk (ubuntu package) and set the JAVA_HOME with the path to this specific version (/usr/lib/jvm/java-19-openjdk-amd64).
However, flutter uses the java binary provided by android studio. You can check that just running:
flutter doctor --verbose
As a solution, I updated the JDK_HOME and STUDIO_JDK environment variables pointing to my java 19 installation.
# inside your .bashrc or .zshrc
export JDK_HOME="$JAVA_HOME"
export STUDIO_JDK="$JAVA_HOME"
source ~/.bashrc # or .zshrc
also, be sure that flutter won't use a different one, I ran:
flutter config --jdk-dir $JAVA_HOME
Then, after logging out from my user, the flutter build and flutter run commands raised no errors.
Here are some useful resources, in case you face a different issue in your project:
Hope it's helped you someway :)