oetoni
oetoni

Reputation: 3867

Flutter: Gradle build failed to produce an .apk file. It's likely that this file was generated under <app_root>\build, but the tool couldn't find it

I am trying to test drive an app. I keep getting a strange issue with this problem as app fail to debug/run. SDK version is 28 while the rest is below:

Flutter 1.13.9-pre.79 • channel master • https://github.com/flutter/flutter.git
Framework • revision 9eb9ea0ffa (6 hours ago) • 2020-01-13 21:30:42 -0800
Engine • revision 0235a50843
Tools • Dart 2.8.0 (build 2.8.0-dev.0.0 28c335d5a2)

enter image description here

Gradle build failed to produce an .apk file. It's likely that this file was generated under C:\Development\\build, but the tool couldn't find it.

Is there a way to pass this issue or a configuration that can allow me to run by providing or giving the output path to Gradle? The .apk seems to generated as the error states.

enter image description here

UPDATE:

Android Studio -v 3.5.3 
Gradle -v 3.4.2 
Gradle Wrapper -v 5.1.1

Upvotes: 137

Views: 146050

Answers (29)

Arham Anees
Arham Anees

Reputation: 168

I came up with the very same error message, using flutter, but the issue wasn't matching any of configuration because I am on mac I had to clear some caches, build files etc to free some space. After freeing the space, I was unable to build my app so it something else. After spending of hours, I came to know that somehow gradlew file inside the android folder is empty. since it is ignored in git, it wasn't showing any changes in changed files and was blocking me. Finally, I copied the content from another project and tried to build and it worked for me.

I know it is weird and may be very rare but it's my case. It may help someone in the future.

Upvotes: 0

0x384c0
0x384c0

Reputation: 2294

If you launch the multi flavor app with flutter run without specifying --flavor on Android, Flutter will execute the assembleDebug Gradle task, which will place the APK in this path:

./build/app/outputs/apk/${flavorName}/debug/app-${flavorName}-debug.apk

Then, for some reason, Flutter expects to find the APK at this path:

./build/app/outputs/flutter-apk/app-debug.apk

As a result, it fails with the following error:

Gradle build failed to produce an .apk file. It's likely that this file was generated under <app_root>\build, but the tool couldn't find it.

To still be able to use the flutter run command without flavor, I resolved this issue by copying the APK to the expected location using Gradle.

Solution:
At the end of your android/app/build.gradle, just add the following:

tasks.configureEach { task ->
    if (task.name == "assembleDebug") {
        task.finalizedBy("copyDebugApkToFlutterExpectedLocation")
    }
}

tasks.register('copyDebugApkToFlutterExpectedLocation') {
    doLast {
        def flavorNames = android.productFlavors.collect { it.name }
        def flavorName = flavorNames.isEmpty() ? "" : flavorNames[0].toLowerCase() // Use the first flavor dynamically

        def debugApkPath = "${buildDir}/outputs/apk/${flavorName}/debug/app-${flavorName}-debug.apk"
        def expectedPath = "${buildDir}/outputs/flutter-apk/app-debug.apk"
        def expectedDir = file(expectedPath).parentFile

        if (file(debugApkPath).exists()) {
            expectedDir.mkdirs()
            copy {
                from debugApkPath
                into expectedDir
                rename { "app-debug.apk" }
            }
            println "Debug APK copied to Flutter expected location: $expectedPath"
        } else {
            println "Debug APK not found at: $debugApkPath"
        }
    }
}

Upvotes: 2

codeaybu
codeaybu

Reputation: 1

 buildTypes {
        release {
            signingConfig = signingConfigs.debug
            debuggable true <---- Delete this line and run flutter build apk again in the terminal
            minifyEnabled true
            shrinkResources true
        }
}

Upvotes: 0

Nithin Khan SS
Nithin Khan SS

Reputation: 71

you first understand what's the error related its because there is no build folder in your flutter root project inside that there is a output folder for apk it's help the application package to run debug and release you have multiple ways to do that easy way is in your android / build . gradle last of the line add

    rootProject.buildDir = '../build'
    subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
    project.evaluationDependsOn(':app')
   }

it will build necessary application package kit if you use android studio you can do this manually

Upvotes: 0

oyenigun
oyenigun

Reputation: 637

I fixed the same issue in my Azure pipeline by changing:

  - task: FlutterBuild@0
        inputs:
          target: 'aab'
          projectDirectory: '.'
          entryPoint: "lib/main.dart"
          iosCodesign: false       

to:

- task: FlutterBuild@0
    inputs:
      target: 'aab'
      projectDirectory: '.'
      entryPoint: "lib/main.dart"
      iosCodesign: false
      extraArgs: '--flavor Development -t lib/main.dart'

Upvotes: 0

Erfan Eghterafi
Erfan Eghterafi

Reputation: 5565

in my case I have a multi flavor app like this (in .vscode/launch.json):

update 04/15/2021:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
            {
                    "name": "YOUR_PROJECT_NAME",
                    "program": "lib/main.dart",
                    "request": "launch",
                    "type": "dart",
                    "args": [
                            "--flavor",
                            "ADD_YOUR_FLAVOR_NAME_HERE" //development or staging or production
                        ]
            }
    ]

Another way:

 android {

    ...

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }

    flavorDimensions "flavor-type"

    productFlavors{
        development{
            dimension "flavor-type"
        }
        staging{
            dimension "flavor-type"
        }
        production{
            dimension "flavor-type"
        }
    }
}

So if you want to run app you have to write the flavor name and then the class name that hold main() function

flutter run --flavor staging -t lib/main_staging.dart

and I solved my error and built the .apk

Upvotes: 195

Suraj Prajapati
Suraj Prajapati

Reputation: 1

run cd android and then run ./gradlew clean this will solve your problem

Upvotes: 0

Jay
Jay

Reputation: 1

I had the same issue.. it turns out I had debuggable set to false in build.gradle file. You can't really run the app in debug mode when debuggable is set to false.

Setting it to true resolved the issue.

debug {
            debuggable true

}

Upvotes: 0

Hadiuzzaman
Hadiuzzaman

Reputation: 454

Step 1: You need to configure flavor from your project/android/app/build.gradle file like this

    defaultConfig {

    flavorDimensions "env"

    productFlavors {
        prod {
            dimension "env"
            applicationIdSuffix ""
            manifestPlaceholders = [appName: "Project Name"]
            applicationId "com.example.prod"

        }
        develop {
            dimension "env"
            manifestPlaceholders = [appName: "[Dev] Project Name"]
            versionNameSuffix ""
            applicationId "com.example.develop"
        }

    }
}

Step 2: Now create separate 2 main file for run different environment like this - folder structure

Here main_develop.dart and main_prod.dart has the same code like this

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

Step 3: Now you are able to run and build different flavor by following those command

  1. Run: flutter run --flavor development -t lib/main_development.dart
  2. Build: flutter build apk --flavor production -t lib/main_production.dart

Upvotes: 6

Navin Kumar
Navin Kumar

Reputation: 4027

This works for me,

flutter run --flavor dev lib/main.dart

Upvotes: 13

Rafik Farhad
Rafik Farhad

Reputation: 1202

I have stuck on this for a week and applied almost everything I found on the internet. At last, upgrading the gradle (also flutter in my case) resolved this. And yes, upgrading gradle has so many consequences, and spent almost a day fixing the build process with the new gradle version. I have bumped the gradle from 7.2 to 8.0 (current latest stable).

Upvotes: 0

ALI HASSAN
ALI HASSAN

Reputation: 1

Go to .vscode then open the launch.json file and add

{
   "name":"app name",
   "request":"launch",
   "type":"dart",
   "flutterMode":"debug",
   "program":"lib/'main of that flavor'",
   "args":[
      "--flavor",
      "<name of flavor'"
   ]
}

Upvotes: 0

Mudasir Habib
Mudasir Habib

Reputation: 848

Steps to follow.

1- cd your_project

2- flutter create .

3- finally flutter run

Upvotes: 1

qix
qix

Reputation: 7902

As others suggested, in my case it was indeed a flavors issue. I checked out a fresh copy of my repo and tried running the app with default settings, which triggered this error. Turns out I forgot to edit my "Run/Debug Configurations", which are stored in Android Studio's settings (.idea/) that are not tracked by my repo. I needed to re-add my flavor options, which was as simple as adding a Flutter configuration (See Run > Edit Configurations... > + button in upper left corner) and specifying its dart entrypoint file+Build flavor name to be able to build anything.

Upvotes: 0

Geoffrey Marizy
Geoffrey Marizy

Reputation: 5521

In my case, it was setting debuggable false in android app build.gradle that caused this issue. I agree not a lot of people are going to modify debuggable configuration, but it might help someone one day to reference this.

 buildTypes {
    debug {
        debuggable false <= causing problem
        ...
    }

Upvotes: 9

moneeb Shammout
moneeb Shammout

Reputation: 1

VIEW IMAGE

Adding the line in the image after the comment in the root android folder build.gradle in subprojects section solved the problem for me

This is the line to add:

project.buildDir = "${rootProject.buildDir}/${project.name}"

Upvotes: 0

Samad Talukder
Samad Talukder

Reputation: 1012

I found out that these lines in build.gradle cause the issue. Then I solved this problem set splits abi enable false

splits{
    abi{
        enable false
        reset()
        include "x86", "x86_64", "armeabi", "armeabi-v7a", "arm64-v8a"
        universalApk false
    }
}

Upvotes: 1

Mir Mahfuz
Mir Mahfuz

Reputation: 733

Add below code in to the app level build.gradle file after buildTypes:

flavorDimensions "flavor"

productFlavors {
    staging {
        dimension "flavor"
    }
}

And Modify your Edit Configurations like below Image : enter image description here

Upvotes: 23

wxkly
wxkly

Reputation: 1381

In my case, I don't add flavor section in gradle files at all. after a few times trying, finally I solved this by adding the following code in root build.gradle file:

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
    project.evaluationDependsOn(':app')
}

Upvotes: 0

MUHAMMAD SHAHID RAFI C P
MUHAMMAD SHAHID RAFI C P

Reputation: 1229

After confirming the android/app/build.gradle have no issues related to flavor, please run command

flutter run --flavor dev lib/main_dev.dart 

instead of

flutter run lib/main_dev.dart --flavor dev 

Upvotes: 24

Tuan Dat Tran
Tuan Dat Tran

Reputation: 453

I found out that these lines in build.gradle cause the issue

splits {
abi {
    enable true
    reset()
    include 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
    universalApk true
}}

and also found out that we don't need it, to build split apk run

flutter build apk --split-per-abi

this will generate v7, v8a & x86_64 automatically

Upvotes: 1

anwar alam
anwar alam

Reputation: 602

I solved my problem by disabling split

splits {

    abi {

        enable false

    }
}

Upvotes: 5

Toot Hzf
Toot Hzf

Reputation: 31

I add the following section to app/build/gradle file , for I only need arm64-v8a versio apk,

splits {
    abi {
        enable true
        reset()
        include 'arm64-v8a'
        universalApk true
    }
}

then the error occurred, so my workaround to fix this just to make a symbol-link named app-debug.apk to the new named app-arm64-v8a-debug.apk in folder build/app/outputs/flutter-apk/ it works!

Upvotes: 2

AlexPad
AlexPad

Reputation: 10879

After a day of struggling to figure out this problem I found where to start to really solve it. Before we insert random code we have to search what is the exact name of the apk it is generating.

Flutter Build Folder -> app -> outputs -> apk

here you will see exactly what the apk name is called if it is in release or debug mode.

In this case if the name has app-staging.apk or some other weird name there is something in your gradle build that is not working well. In my case it was because I had a flavor that was not needed with the name staging.

If this is not the case in your case, then surely it will always be some gradle setting to check. Try to change from release to debug mode or the opposite from "launch.json", in this case you will be able to see if one side and the other not and understand the configuration differences.

Upvotes: 1

JerryZhou
JerryZhou

Reputation: 5166

Ok, I found that it's args in launch.json if you use vscode

enter image description here

Upvotes: 20

Faizan Kamal
Faizan Kamal

Reputation: 2162

I don't know if it is gonna help you or not but I solved my problem by following solution-1.

Solution-1

Replace your project level build.gradle file with following replace the versions and classpath with your own.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.3' 
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

The Most Important Part: Make sure your are using two subprojects

 rootProject.buildDir = '../build'
 subprojects {
     project.buildDir = "${rootProject.buildDir}/${project.name}"
 }
 subprojects {
     project.evaluationDependsOn(':app')
 }

Source

Solution-2

  • Try rebuilding your android files rename the android folder to
    something else to deactivate it like "android-old" or whatever.

  • Then, go in the parent folder of your project, and run below command

       flutter create --org your.organization <your appname>
    

This will rebuild any missing files. That worked for me

Upvotes: 3

Farwa
Farwa

Reputation: 7024

Added the flavor name in Build name from Edit Configurations and it worked! enter image description here

Upvotes: 71

Mahesh
Mahesh

Reputation: 984

Sometimes this issue happens when you have the following code mentioned in build.gradle file. Comment this code and try running the build and it succeeded for me. If you want to build multiple apk files please use them while taking release build and remove it for debug builds. From the screenshot you shared I can see multiple apk generated for you and commenting split apks will help you fix it.

splits {
    abi {
        enable true
        reset()
        include 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        universalApk true
    }
}

Upvotes: 5

Lorenzo Tosone
Lorenzo Tosone

Reputation: 415

In my case, the problem was that a module specific SDK was not set for my Android API module. The solution I found is:

Open Android Studio->File->Project Structure->Project SDK box->set Android API

Upvotes: 3

Related Questions