Как собрать apk файл flutter

Обновлено: 06.07.2024

В привычном цикле разработки Flutter приложения мы запускаем flutter run или используем опции Run или Debug в IDE. По умолчанию Flutter создает версию приложения для отладки.

И вот версия для публикации готова к размещению, например в Google Play Store. Перед тем как публиковать приложение необходимо несколько завершающих штрихов:

  • Добавить иконку приложения (launchpad icon)
  • Подписать приложение (signing)
  • Активировать Proguard
  • Проверить манифест приложения (AndroidManifest.xml)
  • Проверить конфигурацию сборки (build.gradle)
  • Создать версию приложения для публикации (--release)
  • Опубликовать в Google Play Store
  • Еще раз посмотреть Android release FAQ

Иконка приложения

Когда новое Flutter приложение создается, туда добавляется иконка по-умолчанию (логотип Flutter). Для настройки иконки можно воспользоваться пакетом flutter_launcher_icons. Альтернативный вариант, сделать всё самостоятельно, выполнив следующие шаги:

  • Изучить, или хотя бы просмотреть рекомендации и правила Material Design Product icons.
  • В директории <app dir>/android/app/src/main/res/ , поместить файлы иконки в директории соотвествующие соглашению. Стандартные mimmap -директории демонстрируют правильное именование.
  • В файле AndroidManifest.xml в теге application обновить атрибут android:icon для соответствия иконкам (из предыдушего шага), ( для напримера - <application android:icon="@mimap/ic_launcher" .
  • Для проверки, что иконка заменилась, запустить приложение и проверить "иконку запуска"

Подпись приложения

Для публикации приложения в Play Store необходимо подписать приложение цифровой подписью.

Создание хранилища ключей

сохраняйте файл от публичного доступа и конечно не публикуйте его в репозитории проекта
формат файла начиная с версии JAVA 9 по -умолчанию PKS12. Если вы создавали файл ранее, то keytool предложит конвертировать файл в формат PKS12.

Связь хранилища ключей с приложением

Создать файл <app dir>/android/key.properties , который содержит ссылку на хранилище

и здесь тоже, хранить файл key.properties в секрете и не публиковать его в репозиторий проекта

Конфигурация подписи в gradle

в файле <app dir>/android/app/build.gradle

на информацию о файле конфигурации

2. Заменить конфигурацию сборки релиза

на следующую информацию, содержащую параметры подписи

Теперь сборка релиза будет подписываться автоматически.

Активация Proguard

По умолчанию Flutter не проводит обусфикацию и минификацию кода Android. Если есть намерение использовать сторонние библиотеки Java, Kotlin или Android, то имеет смысл снизить размер APK и защитить код от "reverse engineering".

Шаг 1 - конфигурация Proguard

Создать файл /android/app/proguard-rules.pro и добавить правила

Эти правила относятся только ко Flutter, для других библиотек нужны свои собственные правила, ну например для Firebase.

Шаг 2 - активация обусфикации и/или минификации

Откроем /android/app/build.gradle , найдём определение buildTypes . Внутри конфигурации release , добавим minifyEnabled и useProguard , а также укажем файл с конфигурацией Proguard.

конечно минификация и обусфикация увеличать время компиляции файла

Проверим манифест приложения

Проверим манифест приложения, AndroidManifest.xml , размещенный в <app dir>/android/app/src/main и убедимся, что установленные значения корректны:

  • application : отредактируйте android:label в теге application чтобы установить реальное, правильное имя приложения.
  • uses-permissions : Добавьте разрешение android.permissions.INTERNET если приложению требуется доступ в Интернет. Стандартный шаблон приложения не включает этот тег, но позволяет устанавливать соединение в процессе разработки между приложением и инструментами Flutter.

Проверим конфигурацию сборки

Проверить файл конфигурации Gradle, build.gradle , расположенный в <app dir>/android/app и убедиться, что установленные значения верны:

  • defaultConfig
  • applicationId - указан уникальный идентификатор приложения
  • versionCode и versionName : указать внутреннюю версию приложения (число), и строковую версию приложения (для показа пользователям)
  • minSdkVersion и targetSdkVersion : указать минимальный уровнь API, и уровень API для которого было разработано приложение.
versionCode - это положительное число, которое используется в качестве внутренней версии приложения. Это число используется только для определения является ли одна версия более новой чем другая. Чем больше число, тем новее версия. Пользователи не видят эти версии. Максимально допустимое число - 2100000000.
versionName - строка, используемая в качестве номера версии, показываемой пользователям. Единственная цель versionName - отображение пользователю.

Сборка релиза

Есть два возможных варианта публикации в Play Store

Сборка app bundle

Если была произведена настройка подписи, то пакет будет подписан автоматически. Перейти в директорию приложения и выполнить

сейчас (2019) это рекомендованный способ публикации приложений
версии сборки и приложения определяются на основе файла pubspec.yaml . version: 1.0.0+1 - версия приложения это первые три цифры разделенных точками, а версия сборки это число после знака + . Это значения можно переопределить при выполнеии команды используя опции --build-name (versionName) и --build-number (versionCode).

Тестирование app bundle

Есть несколько путей чтобы протестировать app bundle, здесь представлены два

Оффлайн, используя bundle tools

  1. Если еще не имеет bundletools , то получаем это здесь из пакета приложения на присоединенные устройства

Онлайн, используя Google Play

  1. Загрузить пакет в GooglePlay и протестировать. Можно использовать alpha или beta-релизы перед реальной публикацией приложения.

Сборка APK

Несмотря на то, что сборка пакета приложения считается приоритетной перед сборкой APK. Могут быть случаи когда пакеты поддерживаются механизмом распространения. Тогда надо будет выпустить APK для каждой цели ABI (Application Binary Interface).

Если цифровая подпись уже настроена в приложении, все APK будут подписаны:

на выходе получим два APK

  • <app dir>/build/app/outputs/apk/release/app-armeabi-v7a-release.apk
  • <app dir>/build/app/outputs/apk/release/app-arm64-v8a-release.apk

Если убрать опцию --split-per-abi , то получим один "жирный" файл содержащий весь код для всех ABI целей. И пользователю также придется загружать код который не совместим с его платформой.

Для установки APK на устройство, подключим его через USB и выполним команду flutter install

Android release FAQ

Sign up for more like this.

SQLite dumps

Установить SQLite в Ubuntu sudo apt install sqlite3 libsqlite3-devОткрыть конкретную базу данных, консоль: sqlite3

/database.sqlite3 sqlite>Для сохранения дампа базы используется команда .dump: sqlite> .output dump.sql sqlite> .dump sqlite> .exitДля сохранения отдельной таблицы sqlite> .output users.sql sqlite> .dump users sqlite>

Nuxt 3 beta

И так, через 468 дней после первого коммита Nuxt 3 вышел в бета-версии. Более года интенсивной разработки Nuxt 3. Документация и код. Новая основа Помимо Vue3 и Vite, Nuxt 3 содержит новый серверный движок, который открывает новые возможности. Это JavaScript сервер приложений который переносим среди множества современных облачных провайдеров. В

«O» большое - скорость алгоритма

Специальное соглашение «О-большое» описывает скорость работы алгоритма. Важно понимать, знать насколько быстро или медленно работают алгоритмы. Время выполнения алгоритма может расти с разной скоростью. Например при поиске элементов. Допустим один шаг, одна итерация алгоритма выполняется 1мс. Значит при обработке 100 элементов время выполнения будет 100мс. Для бинарного поиска, чтобы найти

During a typical development cycle, you test an app using flutter run at the command line, or by using the Run and Debug options in your IDE. By default, Flutter builds a debug version of your app.

When you’re ready to prepare a release version of your app, for example to publish to the Google Play Store, this page can help. Before publishing, you might want to put some finishing touches on your app. This page covers the following topics:

Note: Throughout this page, [project] refers to the directory that your application is in. While following these instructions, substitute [project] with your app’s directory.

Adding a launcher icon

When a new Flutter app is created, it has a default launcher icon. To customize this icon, you might want to check out the flutter_launcher_icons package.

Alternatively, you can do it manually using the following steps:

Review the Material Design product icons guidelines for icon design.

In the [project]/android/app/src/main/res/ directory, place your icon files in folders named using configuration qualifiers. The default mipmap- folders demonstrate the correct naming convention.

In AndroidManifest.xml , update the application tag’s android:icon attribute to reference icons from the previous step (for example, <application android:icon="@mipmap/ic_launcher" . ).

To verify that the icon has been replaced, run your app and inspect the app icon in the Launcher.

Enabling Material Components

If your app uses Platform Views, you may want to enable Material Components by following the steps described in the Getting Started guide for Android.

  1. Add the dependency on Android’s Material in <my-app>/android/app/build.gradle :

To find out the latest version, visit Google Maven.

  1. Set the light theme in <my-app>/android/app/src/main/res/values/styles.xml :
  1. Set the dark theme in <my-app>/android/app/src/main/res/values-night/styles.xml

Signing the app

To publish on the Play Store, you need to give your app a digital signature. Use the following instructions to sign your app.

On Android, there are two signing keys: deployment and upload. The end-users download the .apk signed with the ‘deployment key’. An ‘upload key’ is used to authenticate the .aab / .apk uploaded by developers onto the Play Store and is re-signed with the deployment key once in the Play Store.

  • It’s highly recommended to use the automatic cloud managed signing for the deployment key. For more information, see the official Play Store documentation.

Create an upload keystore

If you have an existing keystore, skip to the next step. If not, create one by either:

Running the following at the command line:

On Mac/Linux, use the following command:

On Windows, use the following command:

This command stores the upload-keystore.jks file in your home directory. If you want to store it elsewhere, change the argument you pass to the -keystore parameter. However, keep the keystore file private; don’t check it into public source control!

Note:

The keytool command might not be in your path—it’s part of Java, which is installed as part of Android Studio. For the concrete path, run flutter doctor -v and locate the path printed after ‘Java binary at:’. Then use that fully qualified path replacing java (at the end) with keytool . If your path includes space-separated names, such as Program Files , use platform-appropriate notation for the names. For example, on Mac/Linux use Program\ Files , and on Windows use "Program Files" .

The -storetype JKS tag is only required for Java 9 or newer. As of the Java 9 release, the keystore type defaults to PKS12.

Reference the keystore from the app

Warning: Keep the key.properties file private; don’t check it into public source control.

Configure signing in gradle

Configure gradle to use your upload key when building your app in release mode by editing the [project]/android/app/build.gradle file.

Add the keystore information from your properties file before the android block:

Load the key.properties file into the keystoreProperties object.

Find the buildTypes block:

And replace it with the following signing configuration info:

Release builds of your app will now be signed automatically.

Note: You may need to run flutter clean after changing the gradle file. This prevents cached builds from affecting the signing process.

Shrinking your code with R8

R8 is the new code shrinker from Google, and it’s enabled by default when you build a release APK or AAB. To disable R8, pass the --no-shrink flag to flutter build apk or flutter build appbundle .

Note: Obfuscation and minification can considerably extend compile time of the Android application.

Enabling multidex support

When writing large apps or making use of large plugins, you may encounter Android’s dex limit of 64k methods when targeting a minimum API of 20 or below. This may also be encountered when running debug versions of your app via flutter run that does not have shrinking enabled.

Flutter tool supports easily enabling multidex. The simplest way is to opt into multidex support when prompted. The tool detects multidex build errors and will ask before making changes to your Android project. Opting in allows Flutter to automatically depend on androidx.multidex:multidex and use a generated FlutterMultiDexApplication as the project’s application.

Note: Multidex support is natively included when targeting min sdk 21+.

You might also choose to manually support multidex by following Android’s guides and modifying your project’s Android directory configuration. A multidex keep file must be specified to include:

Also, include any other classes used in app startup. See the official Android documentation for more detailed guidance on adding multidex support manually.

Reviewing the app manifest

Review the default App Manifest file, AndroidManifest.xml , located in [project]/android/app/src/main and verify that the values are correct, especially the following:

application Edit the android:label in the application tag to reflect the final name of the app. uses-permission Add the android.permission.INTERNET permission if your application code needs Internet access. The standard template does not include this tag but allows Internet access during development to enable communication between Flutter tools and a running app.

Reviewing the build configuration

Review the default Gradle build file, build.gradle , located in [project]/android/app and verify the values are correct, especially the following values in the defaultConfig block:

applicationId Specify the final, unique (Application Id)appid versionCode & versionName Specify the internal app version number, and the version number display string. You can do this by setting the version property in the pubspec.yaml file. Consult the version information guidance in the versions documentation. minSdkVersion , compilesdkVersion , & targetSdkVersion Specify the minimum API level, the API level on which the app was compiled, and the maximum API level on which the app is designed to run. Consult the API level section in the versions documentation for details. buildToolsVersion Specify the version of Android SDK Build Tools that your app uses. Alternatively, you can use the Android Gradle Plugin in Android Studio, which will automatically import the minimum required Build Tools for your app without the need for this property.

Building the app for release

You have two possible release formats when publishing to the Play Store.

Note: The Google Play Store prefers the app bundle format. For more information, see Android App Bundle and About Android App Bundles.

Warning: Recently, the Flutter team has received several reports from developers indicating they are experiencing app crashes on certain devices on Android 6.0. If you are targeting Android 6.0, use the following steps:

If you build an App Bundle Edit android/gradle.properties and add the flag: android.bundle.enableUncompressedNativeLibs=false .

If you build an APK Make sure android/app/src/AndroidManifest.xml doesn’t set android:extractNativeLibs=false in the <application> tag.

For more information, see the public issue.

Build an app bundle

This section describes how to build a release app bundle. If you completed the signing steps, the app bundle will be signed. At this point, you might consider obfuscating your Dart code to make it more difficult to reverse engineer. Obfuscating your code involves adding a couple flags to your build command, and maintaining additional files to de-obfuscate stack traces.

From the command line:

  1. Enter cd [project]
  2. Run flutter build appbundle
    (Running flutter build defaults to a release build.)

The release bundle for your app is created at [project]/build/app/outputs/bundle/release/app.aab .

By default, the app bundle contains your Dart code and the Flutter runtime compiled for armeabi-v7a (ARM 32-bit), arm64-v8a (ARM 64-bit), and x86-64 (x86 64-bit).

Test the app bundle

An app bundle can be tested in multiple ways—this section describes two.

Offline using the bundle tool

  1. If you haven’t done so already, download bundletool from the GitHub repository.
  2. Generate a set of APKs from your app bundle.
  3. Deploy the APKs to connected devices.

Online using Google Play

  1. Upload your bundle to Google Play to test it. You can use the internal test track, or the alpha or beta channels to test the bundle before releasing it in production.
  2. Follow these steps to upload your bundle to the Play Store.

Build an APK

Although app bundles are preferred over APKs, there are stores that don’t yet support app bundles. In this case, build a release APK for each target ABI (Application Binary Interface).

If you completed the signing steps, the APK will be signed. At this point, you might consider obfuscating your Dart code to make it more difficult to reverse engineer. Obfuscating your code involves adding a couple flags to your build command.

From the command line:

  1. Enter cd [project]
  2. Run flutter build apk --split-per-abi
    (The flutter build command defaults to --release .)

This command results in three APK files:

  • [project]/build/app/outputs/apk/release/app-armeabi-v7a-release.apk
  • [project]/build/app/outputs/apk/release/app-arm64-v8a-release.apk
  • [project]/build/app/outputs/apk/release/app-x86_64-release.apk

Removing the --split-per-abi flag results in a fat APK that contains your code compiled for all the target ABIs. Such APKs are larger in size than their split counterparts, causing the user to download native binaries that are not applicable to their device’s architecture.

Install an APK on a device

Follow these steps to install the APK on a connected Android device.

From the command line:

  1. Connect your Android device to your computer with a USB cable.
  2. Enter cd [project] .
  3. Run flutter install .

Publishing to the Google Play Store

For detailed instructions on publishing your app to the Google Play Store, see the Google Play launch documentation.

Updating the app’s version number

The default version number of the app is 1.0.0 . To update it, navigate to the pubspec.yaml file and update the following line:

The version number is three numbers separated by dots, such as 1.0.0 in the example above, followed by an optional build number such as 1 in the example above, separated by a + .

Both the version and the build number may be overridden in Flutter’s build by specifying --build-name and --build-number , respectively.

In Android, build-name is used as versionName while build-number used as versionCode . For more information, see Version your app in the Android documentation.

After updating the version number in the pubspec file, run flutter pub get from the top of the project, or use the Pub get button in your IDE. This updates the versionName and versionCode in the local.properties file, which are later updated in the build.gradle file when you rebuild the Flutter app.

Android release FAQ

Here are some commonly asked questions about deployment for Android apps.

When should I build app bundles versus APKs?

The Google Play Store recommends that you deploy app bundles over APKs because they allow a more efficient delivery of the application to your users. However, if you’re distributing your application by means other than the Play Store, an APK may be your only option.

What is a fat APK?

A fat APK is a single APK that contains binaries for multiple ABIs embedded within it. This has the benefit that the single APK runs on multiple architectures and thus has wider compatibility, but it has the drawback that its file size is much larger, causing users to download and store more bytes when installing your application. When building APKs instead of app bundles, it is strongly recommended to build split APKs, as described in build an APK using the --split-per-abi flag.

What are the supported target architectures?

When building your application in release mode, Flutter apps can be compiled for armeabi-v7a (ARM 32-bit), arm64-v8a (ARM 64-bit), and x86-64 (x86 64-bit). Flutter does not currently support building for x86 Android (See Issue 9253).

How do I sign the app bundle created by flutter build appbundle ?

How do I build a release from within Android Studio?

In Android Studio, open the existing android/ folder under your app’s folder. Then, select build.gradle (Module: app) in the project panel:

screenshot of gradle build script menu

Next, select the build variant. Click Build > Select Build Variant in the main menu. Select any of the variants in the Build Variants panel (debug is the default):

screenshot of build variant menu

The resulting app bundle or APK files are located in build/app/outputs within your app’s folder.

Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the BSD License.

Flutter can be embedded into your existing Android application piecemeal, as a source code Gradle subproject or as AARs.

The integration flow can be done using the Android Studio IDE with the Flutter plugin or manually.

Warning: Your existing Android app may support architectures such as mips or x86 . Flutter currently only supports building ahead-of-time (AOT) compiled libraries for x86_64 , armeabi-v7a and arm64-v8a .

Consider using the abiFilters Android Gradle Plugin API to limit the supported architectures in your APK. Doing this avoids a missing libflutter.so runtime crash, for example:

The Flutter engine has an x86 and x86_64 version. When using an emulator in debug Just-In-Time (JIT) mode, the Flutter module still runs correctly.

Using Android Studio

The Android Studio IDE is a convenient way of integrating your Flutter module automatically. With Android Studio, you can co-edit both your Android code and your Flutter code in the same project. You can also continue to use your normal IntelliJ Flutter plugin functionalities such as Dart code completion, hot reload, and widget inspector.

Add-to-app flows with Android Studio are only supported on Android Studio 3.6 with version 42+ of the Flutter plugin for IntelliJ. The Android Studio integration also only supports integrating using a source code Gradle subproject, rather than using AARs. See below for more details on the distinction.

Using the File > New > New Module… menu in Android Studio in your existing Android project, you can either create a new Flutter module to integrate, or select an existing Flutter module that was created previously.


If you create a new module, you can use a wizard to select the module name, location, and so on.


The Android Studio plugin automatically configures your Android project to add your Flutter module as a dependency, and your app is ready to build.

Note: To see the changes that were automatically made to your Android project by the IDE plugin, consider using source control for your Android project before performing any steps. A local diff shows the changes.

Tip: By default, your project’s Project pane is probably showing the ‘Android’ view. If you can’t see your new Flutter files in the Project pane, ensure that your Project pane is set to display ‘Project Files’, which shows all files without filtering.

Your app now includes the Flutter module as a dependency. You can jump to the Adding a Flutter screen to an Android app to follow the next steps.

Manual integration

To integrate a Flutter module with an existing Android app manually, without using Flutter’s Android Studio plugin, follow these steps:

Create a Flutter module

Let’s assume that you have an existing Android app at some/path/MyApp , and that you want your Flutter project as a sibling:

This creates a some/path/my_flutter/ Flutter module project with some Dart code to get you started and an .android/ hidden subfolder. The .android folder contains an Android project that can both help you run a barebones standalone version of your Flutter module via flutter run and it’s also a wrapper that helps bootstrap the Flutter module an embeddable Android library.

Note: Add custom Android code to your own existing application’s project or a plugin, not to the module in .android/ . Changes made in your module’s .android/ directory won’t appear in your existing Android project using the module.

Do not source control the .android/ directory since it’s autogenerated. Before building the module on a new machine, run flutter pub get in the my_flutter directory first to regenerate the .android/ directory before building the Android project using the Flutter module.

Note: To avoid Dex merging issues, flutter.androidPackage should not be identical to your host app’s package name

Java 8 requirement

The Flutter Android engine uses Java 8 features.

Before attempting to connect your Flutter module project to your host Android app, ensure that your host Android app declares the following source compatibility within your app’s build.gradle file, under the android < >block, such as:

Add the Flutter module as a dependency

Next, add the Flutter module as a dependency of your existing app in Gradle. There are two ways to achieve this. The AAR mechanism creates generic Android AARs as intermediaries that packages your Flutter module. This is good when your downstream app builders don’t want to have the Flutter SDK installed. But, it adds one more build step if you build frequently.

The source code subproject mechanism is a convenient one-click build process, but requires the Flutter SDK. This is the mechanism used by the Android Studio IDE plugin.

Option A - Depend on the Android Archive (AAR)

This option packages your Flutter library as a generic local Maven repository composed of AARs and POMs artifacts. This option allows your team to build the host app without installing the Flutter SDK. You can then distribute the artifacts from a local or remote repository.

Let’s assume you built a Flutter module at some/path/my_flutter , and then run:

Then, follow the on-screen instructions to integrate.


More specifically, this command creates (by default all debug/profile/release modes) a local repository, with the following files:

To depend on the AAR, the host app must be able to find these files.

To do that, edit app/build.gradle in your host app so that it includes the local repository and the dependency:

Tip: You can also build an AAR for your Flutter module in Android Studio using the Build > Flutter > Build AAR menu.


Your app now includes the Flutter module as a dependency. You can follow the next steps in the Adding a Flutter screen to an Android app.

Option B - Depend on the module’s source code

This option enables a one-step build for both your Android project and Flutter project. This option is convenient when you work on both parts simultaneously and rapidly iterate, but your team must install the Flutter SDK to build the host app.

Tip: By default, the host app provides the :app Gradle project. To change the name of this project, set flutter.hostAppProjectName in the Flutter module’s gradle.properties file. Finally, include this project in the host app’s settings.gradle file mentioned below.

Include the Flutter module as a subproject in the host app’s settings.gradle :

Assuming my_flutter is a sibling to MyApp .

The binding and script evaluation allows the Flutter module to include itself (as :flutter ) and any Flutter plugins used by the module (as :package_info , :video_player , etc) in the evaluation context of your settings.gradle .

Introduce an implementation dependency on the Flutter module from your app:

Your app now includes the Flutter module as a dependency. You can follow the next steps in the Adding a Flutter screen to an Android app.

Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the BSD License.

/media/2021/04/flutter-build-android-apk.jpg

This tutorial shows you how to build APK files for Android for applications developed using Flutter.

APK (Application Package File) is a format used by Android operating systems for distribution and installation. After you build an application, it's quite common to build APK files to be tested across different devices. If the application is developed using Flutter, you can easily build APK files by using flutter build apk command. In this tutorial, I am going to show you how to build APK files for Android using Flutter. This includes how to set the mode (release, debug, or profile), set the main entry point, split per ABI, set target platforms, set the build name and version, build flavor APK, and obfuscate the code.

Set Mode

Build Release APK

By default, if not specified, the generated APK files use release mode.

The above command is the same as the below command which explicitly uses release mode.

Build Debug APK

For debug mode, you need to add --debug flag.

Build Profile APK

For profile mode, you need to add --profile flag.

Set Main Entry-Point File

A Flutter application has a file as the main entry-point. That's the first file to be run when the application is launched (similar to MainActivity in Android). By default, lib/main.dart is set to be the main entry-point. If you want to change that, you can pass --target= flag. The example below changes the entry-point to lib/home.dart

Split per ABI and Set Target Platforms

Android devices use various CPUs. A large portion of devices uses ARM-based CPUs, while some devices use Intel x86 CPUs. In addition, old devices use 32-bit CPUs, while the majority of devices released in recent years already use 64-bit CPUs. Those different CPUs support different instruction sets. By default, Flutter only generates an APK that works for all platforms. But that causes a problem regarding the build size of the APK. It becomes very big in order to support those different instruction sets.

Fortunately, Flutter already provides an easy way to split the APK files per ABIs. You only need to add --split-per-abi flag and Flutter will generate multiple APK files, each for a specific platform.

The result of the above command will generate the below platform-specific APK files.

  • app-arm64-v8a-release.apk
  • app-armeabi-v7a-release.apk
  • app-x86_64-release.apk

Actually, Flutter supports four target platforms: android-arm , android-arm64 , android-x86 , android-x64 . However, android-x86 is not included by default. To specify which target platforms you want to include, you can add --target-platform flag with a comma-separated list of the target platforms as the value. The --split-per-abi flag is still required if you want to generate multiple APK files for different ABIs. Without --split-per-abi flag, it will generate a single APK file that's compatible only for the specified platforms.

At the time this post was written, Flutter doesn't support to build release version for x86 ABI. You can only build the debug version if you want to create an APK that supports x86 devices.

Set Build Name and Version

The build name and build number of a Flutter application is defined in the version property of pubspec.yaml file. The value of version is a three numbers separated by dots which specifies the build name, followed by an optional build number separated by a '+'. For example, version: 1.0.1+2 means the build name is 1.0.1, while the build number is 2. The build name is the one that's shown to the users, while the build version is used as an internal version number.

Changing the version name and number can be done by changing the version property in the pubspec.yaml . There's an alternative way if you want to build APKs with different version name and number from the value in the pubspec.yaml file. You can pass --build-name and --build-number flags to override the value for build name and build version respectively.

Build Flavor APK

An application can have multiple flavors and Flutter also supports to build APK. You can do it by passing --flavor flag. For example, if your application has a flavor named 'pro', the command is

Split Debug Info

Flutter applications use Dart program symbols. To reduce the application size in release build, you can use --split-debug--info command, which is used to store the Dart program symbols in a separate file on the host rather than in the application. The flag requires an argument which specifies the directory where program symbol files are stored. By adding the flag, you need to use flutter symbolize command to obtain a human readable stack trace. The flag cannot be used together with --analyze-size flag.

Code Obfuscation

Code obfuscation is a technique to make the source code more difficult to be read by human. It's usually used to prevent people from reverse engineering your application. Flutter also supports this feature. You can add --obfuscate flag, which must be followed by --split-debug-info flag.

Disable pub get Command

By default, the flutter pub get command will be run every time you run the build command. To disable it, you can add --no-pub flag.

Analyze Size

If you want to analyze the size of a generated APK file, add --analyze-size flag in the command. It only works for release mode and you must specify exactly one platform using --target-platform flag.

Below is the output example of running the above command.

Summary

That's how to build APK files in Flutter. You can run flutter build apk --help to get the list of available flags.

Читайте также: