Display custom elements with the Kotlin Multiplatform SDK
When a screen with a custom element opens, the Adapty SDK passes the element’s Type and ID to a resolver in your app code. The resolver returns one of the following:
- The view that matches the Type and ID: Users see the native view, such as a Lottie animation, an interactive chart, or a camera preview.
- No view: Users see the fallback, which is the content inside the custom element in the Flow & Paywall Builder.
Users of app versions without the resolver also see the fallback. Therefore, you can publish the flow before you release the app.
Before you start
You need:
- Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 or later: Earlier versions show the fallback for every custom element.
- Native code for iOS and Android: The Kotlin Multiplatform SDK has no API for custom elements. Your app passes a resolver to the native Adapty SDK of each platform. Write this code in Swift for iOS and in Kotlin for Android. Add the Swift code to the app target in Xcode, such as
iosApp. Add the Kotlin code to theandroidMainsource set of the module that adds the Adapty SDK, such ascomposeApp. Start each new Kotlin file with thepackageline ofMainActivity.kt. - A naming scheme for custom elements: Give each native view a Type, such as
lottie_animation. Use only lowercase letters, numbers, and underscores in Types. To distinguish between custom elements of the same Type, give each one an ID, such aswelcome_wave. The Types and IDs in your code must match the ones in the Flow & Paywall Builder.
Use the same Types and IDs in your iOS and Android code. Unless you set up a separate audience for each platform, iOS and Android users see the same flows.
Set up your Android project
In the module that adds the Adapty SDK, add the Adapty UI library of the Android SDK. To build native views as composables, also set up Jetpack Compose.
Add the Adapty UI library
In composeApp/build.gradle.kts, add io.adapty:android-ui to the androidMain dependencies, without a version. The Adapty Kotlin Multiplatform SDK sets the version. A different android-ui version can break flows.
kotlin {
sourceSets {
androidMain.dependencies {
implementation("io.adapty:android-ui")
}
}
}Set up Jetpack Compose
A Compose Multiplatform app already has Compose in its Android code. An Android View needs no Compose setup. To build native views as composables in an app without Compose Multiplatform, set up Compose for the Android code of the module.
For the Lottie view on this page, also add com.airbnb.android:lottie-compose to the androidMain dependencies.
Set up your iOS project
Your Swift code calls the native iOS SDK, so your app target needs the AdaptySDK-iOS Swift package. Use the iOS SDK version of the Kotlin Multiplatform SDK: 4.4.1 for 4.4.0-beta.1. This way, your Swift code and the Kotlin Multiplatform SDK use the same version of the iOS SDK.
- In Xcode, go to File > Add Package Dependencies.
- Enter the repository URL:
https://github.com/adaptyteam/AdaptySDK-iOS.git. - From the Dependency Rule dropdown, select Exact Version, and enter
4.4.1. Click Add Package. - In the Choose Package Products window, select AdaptyUI and AdaptyUIBuilder, and add them to your app target, such as
iosApp. Click Add Package.
Create views for custom elements
For each Type, create a native view for iOS and for Android, or reuse one from your native code. The following views of the lottie_animation Type play a Lottie animation. The Android view is a composable that uses the com.airbnb.android:lottie-compose library:
import Lottie
import SwiftUI
struct LottieElementView: View {
let animation: LottieAnimation?
var body: some View {
LottieView(animation: animation)
.resizable()
.looping()
}
}Requirements and best practices
-
Sizing:
- Padding and alignment: Make sure the native view fits the container you allocated for it in the Flow & Paywall Builder, minus the padding. If the view doesn’t take up the entire area, it appears in the top start corner of that area by default. To move it, change the alignment in the Layout section of the custom element.
- Hug height: If the height of the custom element is set to Hug, a view that stretches to fill the available space (like a map or a lazy list) will collapse, or stretch to the height of the screen. Give the custom element a Fixed height instead.
-
Theme: Set colors and fonts in the native code. On Android, to display a composable in the colors and fonts of your app, wrap it in your Compose theme.
-
Flow actions: The native view can’t run flow actions, such as a transition to the next screen. The element context can send messages to the flow, with
sendMessageon iOS andsendon Android, but they’re reserved for future Flow & Paywall Builder capabilities. Keep navigation buttons, purchase buttons, and other buttons with flow actions outside the custom element. -
Selectable elements: Keep the custom element outside product cards and other selectable elements. When the selection changes, the native view can lose its state.
-
Navigation handling: When the user moves to the next screen, the SDK removes the native view from the screen. Stop what the view started, such as camera sessions, players, and location updates:
- SwiftUI view: Use the
onDisappearaction. For async work, use.task: SwiftUI cancels it when the view disappears. - Composable: Use the
onDisposeblock of aDisposableEffect. For async work, useLaunchedEffect: Compose cancels it when the composable leaves the composition. - Android
View: OverrideonDetachedFromWindowin yourViewsubclass, or add aView.OnAttachStateChangeListenerto theView.
When the user comes back, the SDK calls the resolver again, and the native view starts without the state of the previous one. On Android, a rotation makes the SDK call the resolver again.
- SwiftUI view: Use the
-
UIKit views: On iOS, wrap them in
UIViewRepresentable. -
Carousels: On Android, in a carousel, the native views on all slides stay active while the screen is open, not only the view on the visible slide. Keep camera previews and players with sound out of carousels.
Write a resolver to match custom elements and views
Write a resolver for each platform. The resolver receives the Type and ID of a custom element, and returns the matching native view.
To write a resolver, make a type conform to the AdaptyUICustomElementsResolver protocol, and implement the view(forType:id:context:) method.
For the lottie_animation Type, the following resolver returns LottieElementView. The ID names the animation file in the app bundle, such as welcome_wave:
import AdaptyUIBuilder
import Lottie
import SwiftUI
struct CustomElementsResolver: AdaptyUICustomElementsResolver {
func view(
forType type: String,
id: String,
context: AdaptyUICustomElementContext
) -> AnyView? {
switch type {
case "lottie_animation":
// the ID names the animation file, such as welcome_wave.json
guard let animation = LottieAnimation.named(id) else {
return nil // no file for this ID: show the fallback
}
return AnyView(LottieElementView(animation: animation))
default:
return nil
}
}
}In the default case, return nil.
If you add a custom element with a new Type after you release the app, users of the released version see its fallback.
The resolver has the following requirements:
-
Network data and players: Keep network data and players in the state of the native view, not in the resolver. The SDK calls the resolver many times while the screen is open. Code in the resolver runs again on each call, so network requests repeat and players start over. The native view keeps its state between these calls, so the data loads once and the players keep playing. Create players, sessions, and network requests inside the native view:
- SwiftUI view: Create players, sessions, and network requests in
.taskor a@StateObject, not in the initial value of a@Stateproperty. Swift evaluates that initial value again each time the resolver creates the view. - Composable: Create players and sessions in
remember, and network requests inLaunchedEffect. - Android
View: Create players, sessions, and network requests inonAttachedToWindow.
- SwiftUI view: Create players, sessions, and network requests in
-
One native view per custom element: Some native views change while the screen is open, for example, when their data loads or when the user taps them. Implement this logic in the native view itself, not in the resolver. If the resolver returns a different view for the same custom element, the view loses its state.
-
A new
Viewfor each appearance: On Android, create a newViewin each call offactory. The SDK callsfactoryeach time the custom element appears, such as when the screen opens, when the user returns to the screen, or after a rotation. -
App data: Store an object that holds the data, such as an
ObservableObjector aStateFlowwith a daily streak, in a property of the resolver. Pass the object to the native view, and observe the object there:- SwiftUI view: Observe an
ObservableObjectwith@ObservedObject. - Composable: Collect a
StateFlowwithcollectAsState, or observe aLiveDatawithobserveAsState. - Android
View: Observe the object inonAttachedToWindow, and stop inonDetachedFromWindow.
A value that you copy into the resolver, such as the streak number, stays as it was when you created the resolver. If your shared code has the data, such as a daily streak, send each new value to the native code through an interface that each platform implements, and update the object there.
- SwiftUI view: Observe an
Set conditions for fallback content
To show users the fallback content instead of an empty custom element, return no view in the following situations:
- Nothing to visualize — the necessary animation file or data file is missing.
- Nothing to process — the user skipped a quiz question, and the data is incomplete.
- Access prohibited — a denied permission prevents the view from accessing a resource.
For example, the resolver returns no view when the animation file is missing.
To show a native view that needs a permission, ask for the permission on an earlier screen of the flow, with the Request permission action. Then return the native view if the user granted the permission, and no view otherwise. A permission change doesn’t make the SDK call your custom element resolver again, so after a request on the same screen, users still see the fallback. For example, in Show nearby places on a map in a flow, users grant or decline location access on the screen before the map.
Pass the resolver to the SDK
Set the resolver once for each platform, at app launch. The SDK calls it in every flow. Users see your native views in new flows and A/B tests without an app release. These views still show each user their own data, such as a daily streak, because they read that data from your app.
iOS
If your app has no AppDelegate class, add one in iosApp/iosApp/iOSApp.swift, and connect it to your app with @UIApplicationDelegateAdaptor. Import AdaptyUI, and call AdaptyUI.setCustomElementsResolver(_:) in the application(_:didFinishLaunchingWithOptions:) method. If your app already has an AppDelegate class, add the call to it instead. The highlighted lines show what to add:
import AdaptyUI
import SwiftUI
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
AdaptyUI.setCustomElementsResolver(CustomElementsResolver())
// the rest of your launch code
return true
}
}
@main
struct iOSApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}If you write the resolver in iOSApp.swift too, also import AdaptyUIBuilder there.
Android
If your app has no Application class, create MainApplication.kt in the folder of MainActivity.kt, and call AdaptyUI.setCustomElementsResolver in its onCreate method. Import AdaptyUI from com.adapty.ui, the Android SDK, not from com.adapty.kmp. If your app already has an Application class, add the highlighted lines to it instead:
package com.example.app
import android.app.Application
import com.adapty.ui.AdaptyUI
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
AdaptyUI.setCustomElementsResolver(CustomElementsResolver(this))
}
}To make Android create this class at app launch, in composeApp/src/androidMain/AndroidManifest.xml, set the android:name attribute of the application element to .MainApplication. Keep the other attributes as they are:
<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher">To show the same view in every custom element of a Type, pass a map of Types and views instead of a resolver. With a map, you write less code than with a resolver, but you cannot set conditions for fallback content.
The map is a [String: AdaptyUICustomElementBuilder] dictionary. If you write the map in iOSApp.swift, also import Lottie there.
AdaptyUI.setCustomElementsResolver([
"lottie_animation": .init { _, id, _ in LottieElementView(animation: .named(id)) },
])You can’t attach a resolver to one flow. To display data from your shared code, send the data to your native code before the flow opens. Then read the data in the resolver. For example, a paywall displays the weight that the user entered in a previous flow.
Test on a device
The Flow & Paywall Builder can’t run your app code, so its canvas only shows the fallback. An error in the native view can crash the app. Before you release the app, test every screen that has a custom element on an iOS device and on an Android device:
-
To see the latest published version of each flow instead of a cached one, register the device as a test device.
-
To see the warnings of the Adapty SDK in the Xcode console and in Logcat, set the log level to
AdaptyLogLevel.WARNor a more detailed level. -
On the device, run a build that includes the resolver. Open each screen that has a custom element, and verify that the native view appears and fits the custom element. If the view scrolls or responds to drags, test these gestures.
-
If the fallback appears instead of the native view, find this warning in the Xcode console or in Logcat:
custom element <type>:<id> is not served by a resolver. Then verify that:- The Type and ID in the warning match the ones in your code, letter for letter.
- Your app has the file, data, or permission that the view needs.
- Your app sets the resolver at launch: in the
AppDelegateclass on iOS, and on Android, in theApplicationclass thatAndroidManifest.xmlnames.
If the warning doesn’t appear, verify that the app uses Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 or later. On iOS, also verify that the AdaptySDK-iOS package has the version from Set up your iOS project.
-
On Android, if the custom element stays empty, find one of these warnings in Logcat:
custom element <type>:<id> is not served by a resolver: The custom element has no fallback content, and no resolver returns a view for it. Verify each item in step 4.content does not report its size: The composable has no height of its own. Give the custom element a Fixed height.
The SDK only logs the size warning for composables. If an Android
Viewstays empty with no warning, give the custom element a Fixed height too. -
To preview the fallback, return no view for the Type, and open the screen again.
Examples
Each recipe shows the setup in the builder and the code for your app:
- Show user progress with a Lottie animation: A ring that fills as a streak grows.
- Show an interactive weight goal chart in a paywall: A weight goal chart, in the paywall flow that follows the onboarding flow.
- Show nearby places on a map in a flow: A map of fitness centers near each user.