Sub topic 14
Adding native libraries with Gradle and CocoaPods
A plugin often needs more than the platform SDK. You might want an Android client library from Maven Central or an iOS SDK from CocoaPods. This chapter shows where those dependencies are declared, how they reach an app that uses your plugin, and which errors to expect.
This chapter assumes you have the battery_info plugin from earlier chapters, can read a Gradle build file and a podspec, and have a working Android Studio and Xcode setup. The examples use OkHttp on Android and Alamofire on iOS. They stand in for whatever SDK you need.
Where native dependencies live
A Flutter app does not compile your plugin on its own. The Flutter tool adds your plugin's native project to the app's native build, and each platform's package manager resolves the dependencies.
| Platform | File you edit | Resolver | Runs when |
|---|---|---|---|
| Android | `android/build.gradle` (or `build.gradle.kts`) | Gradle | `flutter run`, `flutter build apk` |
| iOS | `ios/battery_info.podspec` | CocoaPods | `pod install`, run by the Flutter tool |
Dependencies belong to the plugin, not to the app. A developer who adds your plugin to pubspec.yaml should never edit native files to make it build.
Android: declaring a Maven dependency
Add the library in the dependencies block of the plugin's android/build.gradle. The generated file differs between Flutter versions, so only the relevant parts are shown here.
android {
namespace 'com.example.battery_info'
compileSdk 34
defaultConfig {
minSdk 21
consumerProguardFiles 'consumer-rules.pro'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
testImplementation 'org.jetbrains.kotlin:kotlin-test'
}Three details matter here.
- Use
implementation, notapi.implementationkeeps the library out of the compile classpath of other modules, so your plugin's Kotlin types do not leak into the app. Useapionly if your public Kotlin types expose the library's classes. - Repositories. The generated file already declares
google()andmavenCentral()for all projects. A library hosted elsewhere needs its repository added there. Prefer public repositories, because every app that uses your plugin must be able to reach them. minSdk. Your plugin'sminSdkmust be at least the library'sminSdk. If it is lower, the app's manifest merge fails with a message thatminSdkVersionof the app cannot be smaller than the library's. Raising the plugin'sminSdkforces every user to raise theirs. Note the new minimum in your README and changelog.
Then use the library from BatteryInfoPlugin.kt like any Kotlin dependency:
import okhttp3.OkHttpClient
class BatteryInfoPlugin : FlutterPlugin, MethodCallHandler {
private val client = OkHttpClient()
// ... channel setup as before
}Local AAR files
A plugin is built as an Android library module. A library module cannot bundle a local .aar through implementation files('libs/vendor.aar'), and the build fails. Publish the AAR to a Maven repository the app can reach. A common choice is a local file-based Maven repository kept inside the plugin. If you control the SDK, publishing it to Maven Central avoids the problem.
Shrinking with R8
Release builds of apps shrink and obfuscate code with R8. Some libraries use reflection and need keep rules. The consumerProguardFiles line in the Gradle file ships a rules file with your plugin, so apps get the rules automatically. Create android/consumer-rules.pro:
-keep class com.example.vendor.sdk.** { *; }Replace the package with the one your library documents. Apps that work in debug but crash in release with ClassNotFoundException or NoSuchMethodError usually need such a rule.
iOS: declaring a pod
The podspec at ios/battery_info.podspec describes your plugin as a pod. Each s.dependency line pulls in another pod.
Pod::Spec.new do |s|
s.name = 'battery_info'
s.version = '0.0.1'
s.summary = 'Reads the battery level on Android and iOS.'
s.description = 'A Flutter plugin that reads the battery level.'
s.homepage = 'https://example.com'
s.license = { :type => 'BSD', :file => '../LICENSE' }
s.author = { 'Example' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.dependency 'Alamofire', '~> 5.8'
s.platform = :ios, '12.0'
s.swift_version = '5.0'
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386'
}
endVersion constraints follow CocoaPods rules. '~> 5.8' allows 5.8 and later 5.x releases but not 6.0. A loose constraint such as '>= 5.0' gives the app freedom, but your code may break against a future release. A tight one such as '= 5.8.1' makes conflicts with the app's own pods likely. The pessimistic operator ~> is usually the best choice.
After editing the podspec, refresh the example app's pods:
cd example/ios
pod install --repo-updateThen import the library in BatteryInfoPlugin.swift with import Alamofire.
Vendored frameworks
If the SDK ships as a binary, place it inside the plugin and reference it in the podspec:
s.vendored_frameworks = 'Frameworks/VendorSDK.xcframework'Use an .xcframework, not an older .framework. An .xcframework contains slices for both devices and simulators, and a plain framework usually cannot build for both.
Swift Package Manager
Recent Flutter versions can also build plugins that use Swift Package Manager. CocoaPods remains the path every Flutter version supports, so this chapter uses the podspec. Check the Flutter documentation for your version before adding a Package.swift.
Keeping versions compatible
The same library can arrive from two directions: your plugin and the app, or two different plugins. Gradle and CocoaPods each pick one version.
| Situation | Gradle behavior | CocoaPods behavior |
|---|---|---|
| Two compatible ranges | Picks the highest requested version | Picks a version satisfying both ranges |
| Incompatible ranges | Still picks the highest, which may break the other consumer at run time | `pod install` fails with a conflict message |
| Same class in two artifacts | Build fails with a duplicate class error | Linker may report duplicate symbols |
This difference affects how you debug. Gradle conflicts often appear late, as a run-time crash. CocoaPods conflicts appear immediately, as an install failure. On Android, run ./gradlew app:dependencies from the example app's android folder to see which version was chosen.
Common errors
Could not resolve com.example:library:1.0. The repository is missing, or the version does not exist. Check the coordinates and therepositoriesblock.minSdkVersion 21 cannot be smaller than version 23 declared in library. The library needs a higherminSdk. Raise the plugin'sminSdk.CocoaPods could not find compatible versions for pod. The ranges of your plugin and the app, or another plugin, do not overlap. Loosen your constraint if the code allows it.The Swift pod ... depends upon ..., which does not define modules. The dependency is an Objective-C pod that lacks module support. Settinguse_modular_headers!in the app's Podfile is a workaround. Better to check whether the pod offers a Swift-friendly release.- Stale pods after a podspec change. Run
pod installagain inexample/ios. If the problem remains, deletePodfile.lockandPods/there and reinstall. - Works in debug, crashes in release on Android. Add keep rules to
consumer-rules.pro.
Exercise
Your plugin's Android code uses a library that needs minSdk 23, and your plugin declares minSdk 21. Which file do you change, what happens if you do nothing, and what else should you update when you fix it?
Show answer
Change minSdk in the defaultConfig block of the plugin's android/build.gradle to 23. If you do nothing, the manifest merge fails when an app with a lower minSdk builds, and the error says the library requires a higher minSdkVersion. Because the change forces every user to raise their own minimum, also record it in the README and the changelog, and bump the plugin version accordingly.
Exercise
You add s.dependency 'Alamofire', '~> 5.8' to the podspec, but the example app still reports that Alamofire is missing. What do you do?
Show answer
Run pod install --repo-update inside example/ios so CocoaPods re-reads the podspec and fetches the pod. If it still fails, remove Pods/ and Podfile.lock in that folder and reinstall. Also check that you imported the module with import Alamofire in the Swift file.