Sub topic 4
Integrating the module into an Android app
This chapter connects the Flutter module you created earlier to an existing Android project. It assumes you can read Gradle build files, know what an Activity and AndroidManifest.xml are, and have a module such as my_flutter_module created with flutter create --template module. Engine caching, entrypoints and platform channels get their own chapters. Here you only need to build the project and show a Flutter screen.
Two ways to depend on the module
Gradle can consume the module in two ways.
| Approach | How it works | Needs Flutter SDK on every build machine | Typical use |
|---|---|---|---|
| Source (subproject) | Your build includes the module's hidden `.android` project | Yes | Teams that work on the Flutter code and the host together |
| AAR | You build the module into Android archives, then depend on them like any library | Only for the person who builds the AAR | Native teams who do not want the Flutter toolchain |
This chapter uses the source approach because it gives the fastest edit-and-run loop. The AAR route is summarized near the end and covered fully in the packaging chapter.
The sample layout puts the module next to the host app, not inside it:
projects/
my_android_app/
my_flutter_module/
.android/
lib/
pubspec.yamlThe relative path from the host to the module matters, because the Gradle script below computes it.
Step 1: Include the module in settings
The module ships a script, .android/include_flutter.groovy. It adds a Gradle project named :flutter and one project for each plugin the module uses. In the host's settings.gradle.kts, apply that script:
// settings.gradle.kts of the host app
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
// Flutter's build adds its own repositories to projects.
// FAIL_ON_PROJECT_REPOS would reject them, so use PREFER_SETTINGS.
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "My Android App"
include(":app")
val filePath = settingsDir.parentFile.toString() + "/my_flutter_module/.android/include_flutter.groovy"
apply(from = File(filePath))If a freshly generated Android Studio project uses FAIL_ON_PROJECT_REPOS, this is the first thing that breaks. The error says a repository was declared by a project even though settings forbid it. Switching the mode, as above, fixes it.
Step 2: Add the dependency and compile options
In app/build.gradle.kts, depend on the :flutter project:
// app/build.gradle.kts
android {
namespace = "com.example.myandroidapp"
compileSdk = 34
defaultConfig {
applicationId = "com.example.myandroidapp"
minSdk = 21
targetSdk = 34
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
}
dependencies {
implementation(project(":flutter"))
}Three details commonly cause trouble:
- minSdk. Flutter sets a minimum API level, and it has changed between releases. Check the value in
my_flutter_module/.android/Flutter/build.gradle. If yourminSdkis lower, the manifest merger fails with a message naming the library that requires a higher level. - Java level. The Flutter embedding is compiled for a recent Java level. If your host still targets Java 8, you will see errors about invoking static or default interface methods. Raise both
compileOptionsandjvmTarget. - Plugins' native code. Every Flutter plugin that your module uses becomes a Gradle project in your host build. Their
minSdkand Java requirements apply too.
Step 3: Declare FlutterActivity
FlutterActivity is the class that owns a Flutter view inside a normal Android Activity. Android needs it declared in the host manifest, because you launch it with an intent:
<!-- app/src/main/AndroidManifest.xml, inside <application> -->
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/Theme.MyAndroidApp"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize" />Each attribute has a purpose:
android:configChangestells Android not to destroy and recreate the activity on rotation, locale change, font scale change and similar events. Flutter handles these itself. Without the attribute, each change rebuilds the activity and the Flutter view along with it.android:hardwareAccelerated="true"is required for Flutter's rendering.android:windowSoftInputMode="adjustResize"makes the keyboard resize the view instead of covering text fields.android:thememust be a theme from your app. It is shown before Flutter draws its first frame.
If you extend FlutterActivity with your own subclass, declare that subclass here instead, using the same attributes.
Step 4: Launch a Flutter screen
The simplest launch creates a new engine on demand and runs the module's main():
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import io.flutter.embedding.android.FlutterActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.open_flutter).setOnClickListener {
startActivity(FlutterActivity.createDefaultIntent(this))
}
}
}createDefaultIntent is shorthand for withNewEngine().build(context). The builder lets you choose how the activity gets its engine:
// New engine, start at a specific route
val cartIntent = FlutterActivity
.withNewEngine()
.initialRoute("/cart")
.build(this)
startActivity(cartIntent)
// Reuse an engine that the Application class already started and cached
val cachedIntent = FlutterActivity
.withCachedEngine("main_engine")
.build(this)
startActivity(cachedIntent)The two modes differ in cost and in lifetime:
| Mode | Engine created | Startup cost | Engine destroyed |
|---|---|---|---|
| `withNewEngine()` | When the activity starts | Pays engine startup and Dart isolate start on each launch, so the screen shows a blank frame first | With the activity |
| `withCachedEngine(id)` | Earlier, by your code | Low, because the engine is already running | Never automatically. You destroy it |
A cached engine ID that is not in FlutterEngineCache makes the activity throw an exception at launch. Put the engine into the cache before any code can start the activity. The Application.onCreate method is the usual place, as the next chapter on caching shows.
The following diagram shows what happens when the user taps the button in the new-engine mode.
Step 5: Build and run
Open the host project in Android Studio and run the app configuration, or use Gradle:
cd my_android_app
./gradlew :app:assembleDebugThe first build is slow because Gradle must also build the module and its plugins. The build needs a Flutter SDK. It finds the SDK through the flutter.sdk entry that Flutter writes into my_flutter_module/.android/local.properties. That file is generated and machine specific, so keep it out of version control. A CI machine needs its own Flutter installation, or you need the AAR approach.
Build types must line up
Your host's debug and release build types map to Flutter's modes. A host debug build runs the Dart code in JIT mode, which supports hot reload. A host release build compiles the Dart code ahead of time. Flutter also has a profile mode. The host does not have one by default, so you add a build type if you want to profile:
android {
buildTypes {
create("profile") {
initWith(getByName("debug"))
matchingFallbacks += listOf("debug", "release")
}
}
}Without matchingFallbacks, dependencies that offer only debug and release variants cannot resolve for the profile type, and Gradle reports that it cannot choose between variants.
Limiting ABIs
Flutter's native libraries are built for several CPU architectures. Release builds support armeabi-v7a, arm64-v8a and x86_64. Debug builds also include x86. If your host restricts abiFilters to something the Flutter engine does not ship, the app crashes at startup with an error that libflutter.so could not be loaded. Keep the filters to the supported set:
android {
defaultConfig {
ndk {
abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86_64")
}
}
}The AAR alternative in brief
If the native team should not need the Flutter SDK, build the module into Maven-style artifacts and point the host at the generated repository:
cd my_flutter_module
flutter build aarThe command prints the exact repository path and dependency lines for each build mode. They look like this in the host's app/build.gradle.kts:
repositories {
maven { url = uri("../my_flutter_module/build/host/outputs/repo") }
maven { url = uri("https://storage.googleapis.com/download.flutter.io") }
}
dependencies {
debugImplementation("com.example.my_flutter_module:flutter_debug:1.0")
releaseImplementation("com.example.my_flutter_module:flutter_release:1.0")
}The trade-off is that you must rebuild the AAR after each Dart change, and hot reload through the normal run flow no longer applies to the Flutter code. The debugging chapter covers how to attach to a running app.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Could not read script ... include_flutter.groovy` | Wrong relative path, or the module's `.android` folder was never generated | Check the path in `settings.gradle.kts`. Run `flutter pub get` in the module |
| Repository declared by project is not allowed | `FAIL_ON_PROJECT_REPOS` in settings | Use `PREFER_SETTINGS` |
| Manifest merger says `minSdkVersion` is too low | Host `minSdk` below Flutter's | Raise `minSdk` |
| Crash on launch about a missing cached engine | The ID is not in `FlutterEngineCache` | Cache the engine before launching |
| App restarts or the Flutter view resets on rotation | `configChanges` missing in the manifest entry | Copy the full attribute list |
| `UnsatisfiedLinkError` for `libflutter.so` | `abiFilters` excludes supported ABIs, or the device has an unsupported ABI | Use the supported filters |
Exercise
Your launch code calls FlutterActivity.withCachedEngine("main_engine").build(this), and the app crashes as soon as the button is tapped. Name two things you would check first.
Show answer
First, check that an engine was put into FlutterEngineCache under exactly the ID "main_engine" (same spelling), and that the code that caches it runs before the tap, for example in Application.onCreate. Second, check that your Application subclass is registered with android:name in the manifest. Otherwise onCreate never runs and the cache stays empty.
Exercise
A teammate adds FlutterActivity to the manifest but leaves out android:configChanges. What behavior will you see, and why?
Show answer
Each rotation, locale change or font scale change makes Android destroy and recreate the activity, which also recreates the Flutter view and can reset the screen's state. With configChanges declared, Android delivers the change to the activity, and Flutter handles it without recreation.