Skip to content

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

FixDevs · (Updated: )

Part of:  Mobile Development Errors

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.

Platform and Environment Differences

Flutter is a cross-platform toolchain, but the build environment is anything but uniform. The same flutter build invocation behaves wildly differently across operating systems and CI runners.

macOS Intel vs Apple Silicon. On Apple Silicon (M1/M2/M3/M4), Xcode and CocoaPods now ship native arm64 binaries, but many older Flutter plugins still bundle Ruby gems and CocoaPods specs compiled for x86_64. When pod install fails with ffi_c.bundle: incompatible architecture or LoadError ... ffi, you are loading an x86_64 gem on arm64 Ruby. Install Ruby through rbenv or chruby instead of using the system Ruby that ships with macOS, then reinstall CocoaPods: gem install cocoapods. Running Xcode itself under Rosetta on Apple Silicon (right-click Xcode → Get Info → Open using Rosetta) is sometimes required for very old plugin code, but it slows clean builds by 30–50%.

Android NDK across machines. Flutter 3.16+ pins a specific NDK version in android/app/build.gradle. If ndkVersion = "26.1.10909125" is set but only NDK 25 is installed in the Android SDK, the Gradle build fails with NDK at /path/to/ndk did not have a source.properties file. Open Android Studio → SDK Manager → SDK Tools → NDK (Side by side) and install the exact requested version, or remove the ndkVersion line to let Gradle pick the installed default.

Linux distros. On Ubuntu 22.04 and 24.04, the default libstdc++ may be too new for older Gradle wrappers. Errors like GLIBC_2.34 not found mean you upgraded the OS but kept a stale gradle-wrapper.properties. Bump the wrapper to Gradle 8.4+ and the Android Gradle Plugin to 8.2+. On Fedora and RHEL derivatives, flutter doctor cannot find Android Studio unless you symlink or alias it explicitly — flatpak-installed Android Studio does not expose its SDK in the path Flutter expects.

Windows native (PowerShell vs cmd). The 260-character MAX_PATH limit hits Flutter projects hard because Gradle build outputs can nest 6–8 levels deep. Errors like Filename too long or unzip: cannot create entry during the Gradle build are almost always this. Enable long paths in the registry (HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled = 1) and add the same to your project’s .gitconfig with git config core.longpaths true. Also use forward slashes in any path you pass to flutter — backslashes inside .dart_tool/ JSON files cause “no such file” errors that vanish when you switch to forward slashes. PowerShell users should set $env:FLUTTER_ROOT explicitly because the installer often writes to User scope while CI scripts read from Machine scope.

WSL2. Flutter for Linux runs inside WSL2, but Android device debugging requires adb to reach a USB device that is owned by the Windows host. Use usbipd-win to bind the device into WSL, or install adb.exe on Windows and forward through socat. Building for iOS from WSL is impossible — Apple’s toolchain demands macOS.

Docker containers. Containerized Android builds require the Android SDK, Java 17 (for AGP 8+), the NDK, and accepted licenses. Use the official cirrusci/flutter image as a base or accept that your custom image must run yes | sdkmanager --licenses once per layer. Pinning the Flutter version in the image avoids the dreaded version solving failed error when CI pulls a newer Flutter than your team’s machines. iOS builds are not possible inside Docker on Linux — only Docker on macOS hosts can drive Xcode.

FVM (Flutter Version Management) across platforms. FVM stores Flutter installations in ~/fvm/versions/ on macOS and Linux, but in %LOCALAPPDATA%\fvm\versions\ on Windows. Committing .fvm/flutter_sdk as a symlink works on Unix but breaks on Windows unless core.symlinks is enabled. Prefer .fvmrc (a JSON file) over the symlink approach for cross-platform teams.

CI runners. GitHub Actions macos-latest upgraded to macOS 14 (arm64) in 2024 — builds that worked on macos-13 may fail on the new runner because the bundled Xcode version jumped from 14.x to 15.x. Pin the runner image (macos-13) or pin Xcode with sudo xcode-select -s /Applications/Xcode_15.4.app. Android builds on ubuntu-latest need java-version: '17' and distribution: 'temurin' in actions/setup-java; the default Java 11 fails immediately with AGP 8+.

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. Corporate proxies frequently intercept services.gradle.org with a TLS-inspecting certificate that Gradle does not trust — export GRADLE_OPTS="-Djavax.net.ssl.trustStore=/path/to/corp.jks" or import the corporate CA into the JVM’s default truststore (cacerts).

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. The same anti-pattern applies to pinning transitive dependencies — every override you add is a future upgrade you will have to manually unblock.

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, set ANDROID_HOME explicitly in your shell profile and re-run — the tool cannot locate a required path until the environment is configured for your specific shell (zsh on macOS, bash on Linux, PowerShell on Windows each load different profile files). 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, mount the pub-cache as a Docker volume between runs to skip re-downloading hundreds of megabytes of Dart packages on every build. Add --cache-from to your docker build and your CI minutes drop noticeably.

Build succeeds locally but fails on a fresh clone

A teammate clones the repo, runs flutter pub get, and the build fails immediately. The usual cause is a generated file checked into source control (or worse, ignored when it should be committed). Verify pubspec.lock is committed, .dart_tool/ is ignored, and ios/Podfile.lock is committed. For iOS-specific Xcode workspace problems on the fresh clone, see Fix: Xcode Build Failed for the signing and provisioning checklist.

Web build fails with “Failed to load resource: net::ERR_FILE_NOT_FOUND”

Flutter web with a non-root base href requires the --base-href flag at build time:

flutter build web --base-href "/myapp/"

The compiled index.html rewrites all asset paths relative to this value. Hosting the resulting build/web/ at the wrong subpath produces 404s for every chunk that look like build failures but are actually deployment misconfigurations.

”Execution failed for task ‘:app:processDebugMainManifest’” after upgrading

AGP 8 enforces that every plugin’s AndroidManifest.xml declares a package attribute or sets a namespace in build.gradle. Older plugins that have not been updated will fail manifest merging. Either upgrade the offending plugin or temporarily pin its version while you wait for a release.


Related: Pin your Flutter SDK version per project with FVM or .tool-versions, keep pubspec.lock and Podfile.lock committed, and run flutter doctor -v before every troubleshooting session to rule out toolchain drift.

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