Skip to content

Fix: Flutter Build Failed – Gradle, CocoaPods, or Dart Compilation Errors

FixDevs ·

Quick Answer

How to fix Flutter build failures including Gradle errors on Android, CocoaPods issues on iOS, Dart compilation errors, and version mismatch problems.

The Error

Your Flutter project fails to build with one of these errors:

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Could not resolve all files for configuration ':app:debugCompileClasspath'.

Or a CocoaPods failure when building for iOS:

Error: CocoaPods's specs repository is too out-of-date to satisfy dependencies.
Error running pod install

Or a Dart compilation error:

Error: The method 'build' isn't defined for the type 'State<MyWidget>'.
lib/main.dart:42:5: Error: Method not found: 'setState'.

Or a version constraint failure:

The current Dart SDK version is 3.2.0.
Because myapp requires SDK version >=3.4.0, version solving failed.
pub get failed

The build process stops before producing an APK, IPA, or desktop binary. The error might come from Gradle (Android), CocoaPods or Xcode (iOS/macOS), the Dart compiler, or the pub dependency resolver.

Why This Happens

Flutter builds involve multiple toolchains working together. When you run flutter build or flutter run, the framework coordinates between the Dart compiler, platform-specific build systems (Gradle for Android, Xcode/CocoaPods for iOS), and the Flutter engine. A failure in any layer stops the entire build.

The most common causes:

  • Gradle version mismatch. The Android build requires a specific Gradle version that matches your Android Gradle Plugin (AGP) version. If either is upgraded without updating the other, the build fails. This is conceptually similar to how Gradle build failures manifest in pure Android/Java projects.
  • CocoaPods out of sync. iOS dependencies managed by CocoaPods need to match the versions specified in Podfile.lock. Running flutter pub get updates Dart dependencies but does not always update the native pods.
  • minSdkVersion too low. A plugin requires a higher Android API level than your project specifies. The error often appears deep in the Gradle output, making it hard to spot.
  • AndroidX migration incomplete. Older Flutter projects or plugins may still reference the legacy Android Support Library, which conflicts with AndroidX.
  • Dart SDK version constraints. Your pubspec.yaml specifies an SDK range that does not match the Dart version bundled with your Flutter installation.
  • Stale build cache. Generated files, cached builds, or platform-specific artifacts become corrupted or outdated after upgrading Flutter or switching branches.
  • Platform channel type mismatches. Native code on the Android or iOS side expects different argument types than the Dart side sends, causing runtime build errors in plugin compilation.

Fix 1: Run Flutter Clean and Rebuild

The first step for almost any Flutter build failure is clearing cached artifacts. Old generated files, stale Gradle caches, and outdated pod installations cause the majority of intermittent build failures:

flutter clean
flutter pub get

For iOS, also clear the CocoaPods cache:

cd ios
rm -rf Pods Podfile.lock
pod install --repo-update
cd ..

For Android, clear the Gradle cache inside the project:

cd android
./gradlew clean
cd ..

Then rebuild:

flutter run

If the error persists after cleaning, the issue is in your configuration, not in stale cache. Continue to the specific fix sections below.

Fix 2: Fix Gradle Version Mismatch (Android)

Gradle build failures on Android usually stem from an incompatible combination of Gradle and the Android Gradle Plugin (AGP). The error looks like:

Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Failed to install the following Android SDK packages as some licences have not been accepted

Or:

Minimum supported Gradle version is 8.0. Current version is 7.5.

Check your current versions. Open android/build.gradle and find the AGP version:

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:8.1.0'
    }
}

Then check android/gradle/wrapper/gradle-wrapper.properties for the Gradle version:

distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-all.zip

Use compatible version pairs. AGP 8.1 requires Gradle 8.0+. AGP 7.4 requires Gradle 7.5+. The official Android documentation lists the full compatibility matrix. Update gradle-wrapper.properties to use a compatible Gradle version:

distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip

Update the AGP version in android/build.gradle if you need a newer Gradle:

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:8.2.0'
    }
}

After changing either version, run:

cd android
./gradlew clean
cd ..
flutter pub get
flutter build apk

If Gradle itself fails to download, check your network and proxy settings. This is the same class of problem as dependency resolution failures in Docker Compose where the build tool cannot fetch required artifacts.

Fix 3: Fix minSdkVersion Errors (Android)

A plugin or dependency requires a higher minimum Android SDK than your project sets. The error looks like:

uses-sdk:minSdkVersion 16 cannot be smaller than version 21 declared in library

Or:

The library requires minimum SDK version 23 but this project declares 19.

Fix — raise your minSdkVersion. Open android/app/build.gradle and update:

android {
    defaultConfig {
        minSdkVersion 23   // was 16 or 19
        targetSdkVersion 34
    }
}

If you use a local.properties or flutter.gradle approach where the min SDK is set via a variable, update it there:

android {
    defaultConfig {
        minSdkVersion localProperties.getProperty('flutter.minSdkVersion', '23').toInteger()
    }
}

In newer Flutter projects (3.16+), the min SDK is often set in android/app/build.gradle via a Flutter-managed variable. Check if your project uses flutter.minSdkVersion in android/local.properties:

flutter.minSdkVersion=23

Pro Tip: To find which plugin requires a specific minSdkVersion, search the build output for the library name. Then check that plugin’s android/build.gradle file in your .pub-cache directory. You can also run flutter pub deps to see the full dependency tree and identify which packages pull in native Android dependencies with higher SDK requirements.

Fix 4: Complete AndroidX Migration

If your project was created before Flutter 1.12 or uses older plugins, you may see errors like:

You might be using a version of the Android Support Library that is incompatible
with the AndroidX dependencies. Consider migrating to AndroidX.

Or class-not-found errors referencing android.support.v4 packages.

Step 1 — Enable AndroidX in gradle.properties:

android.useAndroidX=true
android.enableJetifier=true

The Jetifier converts support-library dependencies to their AndroidX equivalents at build time.

Step 2 — Update imports in Java/Kotlin files. If you have custom platform code in android/app/src/main/, replace:

// Old
import android.support.v7.app.AppCompatActivity;
import android.support.annotation.NonNull;

// New
import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;

Step 3 — Update plugins. Run flutter pub outdated to see which plugins have newer AndroidX-compatible versions, then update them in pubspec.yaml:

flutter pub outdated
flutter pub upgrade

Step 4 — Clean and rebuild:

flutter clean
cd android && ./gradlew clean && cd ..
flutter pub get
flutter build apk

Fix 5: Fix CocoaPods and iOS Build Failures

iOS build failures often involve CocoaPods not resolving, Xcode build settings being misconfigured, or deployment target mismatches.

CocoaPods specs repo outdated:

cd ios
pod repo update
pod install
cd ..

CocoaPods not installed or wrong version:

sudo gem install cocoapods
pod setup
cd ios
pod install

Deployment target mismatch. If a pod requires iOS 13+ but your project targets iOS 11:

Open ios/Podfile and set the platform version:

platform :ios, '13.0'

Also update the project-wide deployment target. Add this to the bottom of your Podfile inside the existing post_install block:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0'
    end
  end
end

Xcode build settings errors. If Xcode reports signing issues, missing provisioning profiles, or architecture problems:

cd ios
rm -rf Pods Podfile.lock
rm -rf .symlinks
cd ..
flutter clean
flutter pub get
cd ios
pod install
cd ..
flutter build ios

For architecture-related errors on Apple Silicon Macs (arm64 vs x86_64 conflicts), add to your Podfile:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'i386'
    end
  end
end

If you also develop native Swift code and encounter nil-related crashes during iOS platform channel integration, see Fix: Swift Fatal Error – Unexpectedly Found Nil for handling optionals safely in your iOS host code.

Fix 6: Fix Dart SDK Version Constraints

When flutter pub get fails with a version solving error, the Dart SDK bundled with your Flutter installation does not match the constraints in pubspec.yaml:

The current Dart SDK version is 3.2.0.
Because myapp requires SDK version >=3.4.0 <4.0.0, version solving failed.

Check your current versions:

flutter --version
dart --version

Option 1 — Upgrade Flutter to get a newer Dart SDK:

flutter upgrade

Or switch to a specific channel:

flutter channel stable
flutter upgrade

Option 2 — Relax the SDK constraint in pubspec.yaml if your code is compatible with older versions:

environment:
  sdk: '>=3.0.0 <4.0.0'

Option 3 — Use Flutter Version Manager (FVM) to manage multiple Flutter versions per project:

dart pub global activate fvm
fvm install 3.22.0
fvm use 3.22.0
fvm flutter pub get

This is useful when different projects require different Flutter/Dart versions.

Fix 7: Fix Pub Get and Dependency Resolution Failures

When flutter pub get fails with dependency conflicts:

Because package_a >=2.0.0 depends on package_b ^3.0.0 and package_c >=1.0.0
depends on package_b ^2.0.0, package_a >=2.0.0 is incompatible with package_c >=1.0.0.

Step 1 — See what is outdated:

flutter pub outdated

This shows a table of current, upgradable, resolvable, and latest versions for every dependency.

Step 2 — Try upgrading all packages:

flutter pub upgrade --major-versions

This updates pubspec.yaml constraints and fetches the latest compatible versions.

Step 3 — Use dependency overrides as a temporary fix when two packages require conflicting versions of a shared dependency:

dependency_overrides:
  package_b: ^3.0.0

Common Mistake: Leaving dependency_overrides in your pubspec.yaml permanently. Overrides bypass version solving safety checks and can cause subtle runtime errors. Use them only to unblock development, and remove them as soon as the upstream packages publish compatible versions. This is similar to how forcing environment variables without validation leads to hard-to-debug issues.

Step 4 — Delete the lock file and resolve fresh if the dependency cache is corrupted:

rm pubspec.lock
flutter pub get

Fix 8: Fix Platform Channel Errors

Platform channels let Dart code communicate with native Android (Kotlin/Java) and iOS (Swift/Objective-C) code. Type mismatches or missing method handlers cause build or runtime errors:

MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.dev/battery)

Check that the native side registers the channel. In Android (MainActivity.kt):

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val CHANNEL = "samples.flutter.dev/battery"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
            .setMethodCallHandler { call, result ->
                if (call.method == "getBatteryLevel") {
                    result.success(getBatteryLevel())
                } else {
                    result.notImplemented()
                }
            }
    }
}

In iOS (AppDelegate.swift):

import Flutter
import UIKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        let controller = window?.rootViewController as! FlutterViewController
        let channel = FlutterMethodChannel(
            name: "samples.flutter.dev/battery",
            binaryMessenger: controller.binaryMessenger
        )
        channel.setMethodCallHandler { (call, result) in
            if call.method == "getBatteryLevel" {
                result(self.getBatteryLevel())
            } else {
                result(FlutterMethodNotImplemented)
            }
        }
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

Ensure the channel name matches exactly between Dart and native code. A single character difference causes the MissingPluginException.

Ensure type consistency. Dart int maps to Java Integer/Kotlin Int, Dart String maps to String, Dart Map maps to HashMap. Passing a type that the native side does not expect causes serialization errors during compilation or at runtime.

Fix 9: Run Flutter Doctor

flutter doctor is the single most useful diagnostic command. It checks your Flutter installation, connected devices, IDE configuration, and platform toolchains:

flutter doctor -v

The output flags every issue with a clear description:

[✓] Flutter (Channel stable, 3.22.0)
[✗] Android toolchain - develop for Android devices
    ✗ Android SDK not found at /Users/you/Library/Android/sdk
    ✗ No valid Android SDK platforms found
[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
[✗] Chrome - develop for the web (Cannot find Chrome executable)
[✓] Android Studio (version 2024.1)
[✓] VS Code (version 1.91.0)
[✓] Connected device (2 available)
[✓] Network resources

Fix every item marked with an X. Common fixes:

# Accept Android SDK licenses
flutter doctor --android-licenses

# Install missing command-line tools
sdkmanager --install "cmdline-tools;latest"

# Set ANDROID_HOME if the SDK is not found
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$PATH

If flutter doctor reports that the Android SDK is not found, this is the same type of issue as missing environment variables in other build systems — the tool cannot locate a required path because the environment is not configured. For Java heap space errors during Android builds, see Fix: Java OutOfMemoryError for how to increase JVM memory limits.

Still Not Working?

The build fails only on CI/CD

CI environments often have different Flutter versions, missing Android SDK components, or no Xcode installation. Pin your Flutter version in CI using FVM or by downloading a specific Flutter archive. Ensure your CI script runs flutter doctor -v early so you can see exactly what is missing. Also check that the CI runner has enough memory — Android Gradle builds are memory-hungry and may fail with out-of-memory errors on constrained runners.

The build succeeds locally but fails for a teammate

Different Flutter versions across machines cause inconsistent builds. Use .fvmrc or .tool-versions to pin the Flutter version for the entire team:

{
  "flutter": "3.22.0"
}

Also commit pubspec.lock to source control so everyone uses the same resolved dependency versions. Do not add pubspec.lock to .gitignore for application projects.

Plugin compilation errors after upgrading Flutter

After a major Flutter upgrade, plugins compiled against the old Flutter engine may fail. Run:

flutter pub outdated
flutter pub upgrade --major-versions

If a specific plugin has no compatible update yet, check its GitHub repository for open issues or pre-release versions. You can temporarily pin the older version in pubspec.yaml while waiting for an update.

Build fails with “Dart SDK version not supported”

Your global Dart installation may shadow the one bundled with Flutter. Ensure that flutter/bin appears before any standalone Dart SDK in your PATH. Run which dart (or where dart on Windows) to verify:

which dart
# Should point to: /path/to/flutter/bin/dart
# NOT: /usr/local/bin/dart or /opt/homebrew/bin/dart

If the wrong Dart is first in your path, reorder your PATH variable or remove the standalone Dart installation.

iOS build fails with “module not found” or “framework not found”

This usually means CocoaPods installed the pods but Xcode cannot find them. Reset the Xcode workspace:

cd ios
rm -rf Pods Podfile.lock .symlinks
rm -rf ~/Library/Developer/Xcode/DerivedData
pod install --repo-update
cd ..
flutter clean
flutter build ios

If you are working in a Dockerized environment for CI builds and encounter filesystem or permission issues during the build, see Fix: Docker Compose Up Errors for troubleshooting container-based build pipelines.


Related: Fix: Gradle Build Failed | Fix: Swift Fatal Error – Unwrapping Nil | Fix: Java OutOfMemoryError

F

FixDevs

Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.

Was this article helpful?

Related Articles