Skip to content

Commit 52ac893

Browse files
authored
Add java/gradle check when gradle crashes (flutter#189997)
Adds a check for Java/Gradle compatibility after gradle crashes. If the two are incompatible, Gradle can't even start up to run the DependencyVersionChecker.kt - so it throws a cryptic error. Partially address: flutter#189780 Before ``` ❯ flutter config --jdk-dir=/opt/homebrew/opt/openjdk@25/libexec/openjdk.jdk/Contents/Home Setting "jdk-dir" value to "/opt/homebrew/opt/openjdk@25/libexec/openjdk.jdk/Contents/Home". You may need to restart any open editors for them to read new settings. ❯ flutter build apk WARNING: A restricted method in java.lang.System has been called WARNING: java.lang.System::load has been called by net.rubygrapefruit.platform.internal.NativeLibraryLoader in an unnamed module (file:/Users/boetger/.gradle/wrapper/dists/gradle-8.14-all/c2qonpi39x1mddn7hk5gh9iqj/gradle-8.14/lib/native-platform-0.22-milestone-28.jar) WARNING: Use --enable-native-access=ALL-UNNAMED to avoid a warning for callers in this module WARNING: Restricted methods will be blocked in a future release unless native access is enabled FAILURE: Build failed with an exception. * What went wrong: 25.0.4 * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. BUILD FAILED in 321ms ``` After ``` ❯ flutter config --jdk-dir=/opt/homebrew/opt/openjdk@25/libexec/openjdk.jdk/Contents/Home Setting "jdk-dir" value to "/opt/homebrew/opt/openjdk@25/libexec/openjdk.jdk/Contents/Home". You may need to restart any open editors for them to read new settings. ❯ flutter build apk Gradle build failed due to Java/Gradle incompatibility. The Java version used for the build is 25.0.4, which is incompatible with Gradle 8.14. To fix this, you can either: 1. Upgrade your project's Gradle version (typically in gradle-wrapper.properties to a version matching the range: compatible Gradle versions for Java 25.0.4 are 9.1.0 to newer). 2. Use a different Java version for Flutter by running `flutter config --jdk-dir=<path>`. Alternatively, you can bypass this check using "--android-skip-build-dependency-validation". ``` ## Pre-launch Checklist - [X] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [X] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [X] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [X] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [X] I signed the [CLA]. - [X] I listed at least one issue that this PR fixes in the description above. - [X] I updated/added relevant documentation (doc comments with `///`). - [X] I added new tests to check the change I am making, or this PR is [test-exempt]. - [X] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [X] All existing and new tests are passing.
1 parent 0c52dee commit 52ac893

3 files changed

Lines changed: 401 additions & 38 deletions

File tree

‎packages/flutter_tools/lib/src/android/gradle.dart‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import '../base/process.dart';
2525
import '../base/project_migrator.dart';
2626
import '../base/terminal.dart';
2727
import '../base/utils.dart';
28+
import '../base/version.dart';
2829
import '../build_info.dart';
2930
import '../cache.dart';
3031
import '../convert.dart';
@@ -431,6 +432,56 @@ class AndroidGradleBuilder implements AndroidBuilder {
431432
return exitCode;
432433
}
433434

435+
// Validate Java and Gradle compatibility after Gradle fails.
436+
// This check is done in Dart after a Gradle crash because:
437+
// 1. If Java and Gradle are incompatible, Gradle can crash during build script
438+
// compilation (e.g. Kotlin DSL compilation failing on newer JDKs) before
439+
// the Flutter Gradle Plugin (DependencyVersionChecker) is even applied.
440+
// See https://github.com/flutter/flutter/issues/189780 for context on
441+
// how JDK upgrades lead to cryptic Gradle compilation crashes.
442+
// 2. Checking only after Gradle crashes avoids blocking builds that currently
443+
// succeed despite an unsupported Java/Gradle version pair.
444+
// 3. This also helps address https://github.com/flutter/flutter/issues/167931
445+
// by providing actionable version recommendations directly in the error.
446+
Future<void> _checkJavaAndGradleCompatibility(FlutterProject project, BuildInfo buildInfo) async {
447+
if (!buildInfo.androidSkipBuildDependencyValidation) {
448+
final Version? javaVersionObj = _java?.version;
449+
final String? javaVersion = javaVersionObj != null
450+
? '${javaVersionObj.major}.${javaVersionObj.minor}.${javaVersionObj.patch}'
451+
: null;
452+
final String? gradleVersion = await getGradleVersionFromFile(
453+
project.android.hostAppGradleRoot,
454+
_logger,
455+
);
456+
if (javaVersion != null && gradleVersion != null) {
457+
if (!gradle.validateJavaAndGradle(
458+
_logger,
459+
javaVersion: javaVersion,
460+
gradleVersion: gradleVersion,
461+
)) {
462+
final JavaGradleCompat? compat = gradle.getValidGradleVersionRangeForJavaVersion(
463+
_logger,
464+
javaV: javaVersion,
465+
);
466+
final gradleRangeMax = compat != null && compat.gradleMax != null
467+
? ' to ${compat.gradleMax}'
468+
: '';
469+
final gradleRangeCompatSuggestion = compat != null
470+
? '${compat.gradleMin}$gradleRangeMax or newer'
471+
: 'unknown';
472+
final gradleRangeInfo =
473+
'compatible Gradle versions for Java $javaVersion are $gradleRangeCompatSuggestion';
474+
throwToolExit("""
475+
Gradle build failed due to Java/Gradle incompatibility.
476+
The Java version used for the build is $javaVersion, which is incompatible with Gradle $gradleVersion.
477+
To fix this, you can either:
478+
1. Upgrade your project's Gradle version (typically in gradle-wrapper.properties to a version matching the range: $gradleRangeInfo).
479+
2. Use a different Java version for Flutter by running `flutter config --jdk-dir=<path>`.""");
480+
}
481+
}
482+
}
483+
}
484+
434485
/// Builds an app.
435486
///
436487
/// * [project] is typically [FlutterProject.current()].
@@ -598,6 +649,7 @@ class AndroidGradleBuilder implements AndroidBuilder {
598649
);
599650

600651
if (exitCode != 0) {
652+
await _checkJavaAndGradleCompatibility(project, androidBuildInfo.buildInfo);
601653
throwToolExit(
602654
'Gradle task $assembleTask failed with exit code $exitCode',
603655
exitCode: exitCode,
@@ -896,6 +948,7 @@ class AndroidGradleBuilder implements AndroidBuilder {
896948
if (result.exitCode != 0) {
897949
_logger.printStatus(result.stdout, wrap: false);
898950
_logger.printError(result.stderr, wrap: false);
951+
await _checkJavaAndGradleCompatibility(project, androidBuildInfo.buildInfo);
899952
throwToolExit(
900953
'Gradle task $aarTask failed with exit code ${result.exitCode}.',
901954
exitCode: result.exitCode,

‎packages/flutter_tools/lib/src/android/gradle_utils.dart‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -331,16 +331,11 @@ String? parseGradleVersionFromDistributionUrl(String? distributionUrl) {
331331
return zipParts[1];
332332
}
333333

334-
/// Returns either the gradle-wrapper.properties value from the passed in
335-
/// [directory] or if not present the version available in local path.
334+
/// Returns the gradle-wrapper.properties value from the passed in [directory].
336335
///
337-
/// If gradle version is not found null is returned.
338-
/// [directory] should be an android directory with a build.gradle file.
339-
Future<String?> getGradleVersion(
340-
Directory directory,
341-
Logger logger,
342-
ProcessManager processManager,
343-
) async {
336+
/// If gradle version is not found in the file, null is returned.
337+
/// [directory] should be an android directory.
338+
Future<String?> getGradleVersionFromFile(Directory directory, Logger logger) async {
344339
final File propertiesFile = getGradleWrapperFile(directory);
345340

346341
if (propertiesFile.existsSync()) {
@@ -357,14 +352,30 @@ Future<String?> getGradleVersion(
357352
}
358353
} else {
359354
// If no distributionUrl log then treat as if there was no propertiesFile.
360-
logger.printTrace(
361-
'$propertiesFile does not provide a Gradle version falling back to system gradle.',
362-
);
355+
logger.printTrace('$propertiesFile does not provide a Gradle version.');
363356
}
364357
} else {
365358
// Could not find properties file.
366-
logger.printTrace('$propertiesFile does not exist falling back to system gradle');
359+
logger.printTrace('$propertiesFile does not exist.');
360+
}
361+
return null;
362+
}
363+
364+
/// Returns either the gradle-wrapper.properties value from the passed in
365+
/// [directory] or if not present the version available in local path.
366+
///
367+
/// If gradle version is not found null is returned.
368+
/// [directory] should be an android directory with a build.gradle file.
369+
Future<String?> getGradleVersion(
370+
Directory directory,
371+
Logger logger,
372+
ProcessManager processManager,
373+
) async {
374+
final String? gradleVersion = await getGradleVersionFromFile(directory, logger);
375+
if (gradleVersion != null) {
376+
return gradleVersion;
367377
}
378+
logger.printTrace('Falling back to system gradle');
368379
// System installed Gradle version.
369380
// TODO(reidbaker): Modify this gradle execution to use gradlew.
370381
if (processManager.canRun('gradle')) {

0 commit comments

Comments
 (0)