---
title: "Afficher un graphique interactif d'objectif de poids dans un paywall"
description: "Affichez le poids projeté de chaque utilisateur sous forme de graphique dans un flow de paywall. Les utilisateurs font glisser le graphique pour voir le poids à n'importe quelle semaine."
---

> For the complete documentation index, see [llms.txt](https://adapty.io/docs/fr/llms.txt).

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

Suivez cette recette pour afficher le poids projeté de chaque utilisateur sous forme de graphique dans un flow paywall. L'utilisateur saisit son poids actuel et son poids cible dans un flow d'onboarding. Votre application collecte ces deux valeurs. Le graphique montre la progression hebdomadaire que l'utilisateur peut espérer avec votre application, de l'une à l'autre. Votre application affiche le graphique comme une vue native dans un [élément personnalisé](flow-custom-elements). Sur iOS, la vue utilise Swift Charts. Sur Android, la vue dessine le graphique sans bibliothèque de graphiques.

## Avant de commencer \{#before-you-start\}

- Mettez à jour votre application vers le SDK Adapty Kotlin Multiplatform 4.4.0-beta.1 ou ultérieur. Les versions antérieures du SDK affichent le [contenu de secours](flow-custom-elements#set-fallback-content) pour chaque élément personnalisé.
- Configurez votre application pour [récupérer](kmp-get-pb-paywalls) et [afficher](kmp-present-paywalls) les flows.
- Configurez le code natif de votre application pour les éléments personnalisés, comme indiqué dans le [guide Kotlin Multiplatform](kmp-flow-custom-elements#before-you-start).
- Sur iOS, le défilement le long du graphique nécessite iOS 17 ou ultérieur. Sur iOS 16, les utilisateurs voient la ligne, mais ne peuvent pas la faire glisser.
- Sur Android, [configurez votre projet Android](kmp-flow-custom-elements#set-up-your-android-project), y compris Jetpack Compose. Le graphique dans cette recette est un composable. Si votre application n'utilise pas Compose Multiplatform, ajoutez Compose Foundation aux dépendances `androidMain`, depuis `androidx.compose.foundation:foundation`, sans version. Le BOM Compose de `io.adapty:android-ui` définit la version.

Créez deux flows distincts — un pour l'onboarding, et un pour le paywall. Ajoutez chacun à un [placement](placements). Le code de cette recette récupère le flow du paywall depuis le placement avec l'ID `weight_paywall`.

## 1. Demandez le poids actuel et l'objectif dans le flow d'onboarding \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

Dans le Flow & Paywall Builder, ajoutez deux saisies [**Number**](builder-inputs-and-forms) à l'onboarding flow :

- Une pour le poids actuel en kilogrammes, avec l'**Element ID** `weight`.
- Une pour le poids cible en kilogrammes, avec l'**Element ID** `goal_weight`.

Pour que votre application lise les poids de la même façon dans toutes les langues, sélectionnez **Integer** dans le menu déroulant **Format** des deux saisies. Une saisie envoie sa valeur à votre application sous forme de texte, exactement tel que l'utilisateur l'a tapé. Le code de cette recette interprète « 70.5 » et « 70,5 » différemment. Les nombres entiers n'ont pas de séparateur décimal.

Pour vous assurer que votre application reçoive les deux valeurs, terminez l'onboarding flow par un écran sans saisies. Sur cet écran, ajoutez un bouton avec l'action [**Close flow**](onboarding-actions#close-flow). Les saisies envoient leurs valeurs lorsqu'elles perdent le focus ou lorsque l'utilisateur passe à un autre écran.

## 2. Ajouter l'élément personnalisé à l'écran du paywall \{#2-add-the-custom-element-to-the-paywall-screen\}

Dans le flow du paywall, [ajoutez un élément personnalisé](flow-custom-elements#add-and-configure) à un écran et configurez-le pour le graphique :

- **Type** : `line_chart`.
- **ID** : `weight_goal`.
- **Hauteur** : Conservez la hauteur **Fixed** par défaut. Le graphique remplit l'élément personnalisé.

Ne placez pas l'élément personnalisé dans des conteneurs qui répondent au toucher, comme un carousel, afin que seul le graphique réagisse au glissement.

À l'intérieur de l'élément personnalisé, ajoutez une [**Image**](custom-media#image) avec un exemple de graphique de poids. Les utilisateurs la voient comme [contenu de secours](flow-custom-elements#set-fallback-content) lorsque leur version de votre application n'affiche pas le graphique.

## 3. Enregistrez le poids actuel et l'objectif dans votre application \{#3-save-the-current-and-goal-weight-in-your-app\}

Récupérez le poids actuel et l'objectif à partir des événements `flow_user_input` de l'onboarding flow, comme indiqué dans [Traiter les données des flows](kmp-flow-input). Pour savoir que l'utilisateur a atteint le dernier écran, surveillez un événement `flow_screen_showed` avec `is_last_screen` défini à `true`. Lorsque l'onboarding flow se ferme après cet écran, transmettez le poids actuel et l'objectif à `showWeightPaywall`, la fonction qui [ouvre le flow de paywall avec le graphique](#6-send-the-current-and-goal-weight-from-your-shared-code).

Un seul observateur reçoit les événements des deux flows. Enregistrez-le avec `AdaptyUI.setFlowsEventsObserver` avant de présenter le flow d'onboarding. L'observateur que vous enregistrez remplace le précédent : si votre application en enregistre déjà un, ajoutez le code de `WeightFlowsObserver` au vôtre. La fonction `showWeightPaywall` provient de [l'étape 6](#6-send-the-current-and-goal-weight-from-your-shared-code).

```kotlin showLineNumbers title="commonMain"

class WeightFlowsObserver : AdaptyUIFlowsEventsObserver {
    private val enteredWeights = mutableMapOf<String, String>()
    private var reachedLastScreen = false

    override fun flowViewDidReceiveAnalyticEvent(
        view: AdaptyUIFlowView,
        name: String,
        paramsJsonString: String,
    ) {
        val params = Json.parseToJsonElement(paramsJsonString).jsonObject
        if (name == "flow_screen_showed" && params["is_last_screen"]?.jsonPrimitive?.booleanOrNull == true) {
            reachedLastScreen = true
            return
        }
        if (name != "flow_user_input") return
        val elementId = params["element_id"]?.jsonPrimitive?.contentOrNull ?: return
        val value = params["value"]?.jsonPrimitive?.contentOrNull ?: return
        enteredWeights[elementId] = value
    }

    override fun flowViewDidDisappear(view: AdaptyUIFlowView) {
        // This observer receives events from both flows. Reset the entered
        // current and goal weight whenever a flow disappears, so that the paywall doesn't open
        // again when the user closes it.
        val weights = enteredWeights.toMap()
        val finished = reachedLastScreen
        enteredWeights.clear()
        reachedLastScreen = false

        // number inputs send their values as strings
        val currentWeight = weights["weight"]?.toDoubleOrNull()
        val goalWeight = weights["goal_weight"]?.toDoubleOrNull()
        if (!finished || currentWeight == null || goalWeight == null) return

        showWeightPaywall(currentWeight, goalWeight) // defined in step 6
    }
}

// call at app launch, before you present the onboarding flow
fun registerWeightFlowsObserver() {
    AdaptyUI.setFlowsEventsObserver(WeightFlowsObserver())
}
```

## 4. Créer la vue du graphique \{#create-the-chart-view\}

Créez un modèle de plan de poids et une vue avec le graphique. Le plan comporte une entrée par semaine, du poids actuel jusqu'au poids cible. Lorsque l'utilisateur fait glisser son doigt sur le graphique, la vue marque la semaine au point de contact et affiche le poids prévu pour cette semaine :

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift"

struct WeightPlan {
    let entries: [WeightEntry]

    // One entry per week, from the current weight to the goal weight
    init(currentWeight: Double, goalWeight: Double) {
        let weeklyChange = 0.5 // kg per week
        let startDate = Date.now
        let weeks = Int((abs(goalWeight - currentWeight) / weeklyChange).rounded(.up))
        let step = goalWeight < currentWeight ? -weeklyChange : weeklyChange
        entries = (0...weeks).map { week in
            WeightEntry(
                date: startDate.addingTimeInterval(Double(week) * 7 * 24 * 60 * 60),
                kilograms: week == weeks ? goalWeight : currentWeight + step * Double(week)
            )
        }
    }
}

struct WeightEntry: Identifiable {
    let date: Date
    let kilograms: Double
    var id: Date { date }
}

@available(iOS 16.0, *) // Swift Charts needs iOS 16
struct WeightGoalChart: View {
    let entries: [WeightEntry]
    @State private var selectedDate: Date?

    // The entry closest to the date that the user drags to
    private var selectedEntry: WeightEntry? {
        guard let selectedDate else { return nil }
        return entries.min {
            abs($0.date.timeIntervalSince(selectedDate)) < abs($1.date.timeIntervalSince(selectedDate))
        }
    }

    var body: some View {
        if #available(iOS 17.0, *) {
            chart.chartXSelection(value: $selectedDate)
        } else {
            chart // iOS 16: no drag selection
        }
    }

    private var chart: some View {
        Chart {
            ForEach(entries) { entry in
                LineMark(
                    x: .value("Date", entry.date),
                    y: .value("Weight", entry.kilograms)
                )
            }
            if let selectedEntry {
                RuleMark(x: .value("Date", selectedEntry.date))
                    .foregroundStyle(.gray.opacity(0.3))
                PointMark(
                    x: .value("Date", selectedEntry.date),
                    y: .value("Weight", selectedEntry.kilograms)
                )
                .annotation(position: .top) {
                    Text("\(selectedEntry.kilograms, specifier: "%.1f") kg")
                        .font(.caption.bold())
                }
            }
        }
        .chartYScale(domain: .automatic(includesZero: false))
    }
}
```

Le défilement sur le graphique nécessite iOS 17 ou une version ultérieure. Sur iOS 16, les utilisateurs voient la ligne, mais ne peuvent pas la faire glisser.

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin"

class WeightPlan(currentWeight: Double, goalWeight: Double) {
    // one entry per week, from the current weight to the goal weight
    val entries: List<WeightEntry> = run {
        val weeklyChange = 0.5 // kg per week
        val start = System.currentTimeMillis()
        val weekMillis = 7L * 24 * 60 * 60 * 1000
        val weeks = ceil(abs(goalWeight - currentWeight) / weeklyChange).toInt()
        val step = if (goalWeight < currentWeight) -weeklyChange else weeklyChange
        (0..weeks).map { week ->
            val kilograms = if (week == weeks) goalWeight else currentWeight + step * week
            WeightEntry(Date(start + week * weekMillis), kilograms)
        }
    }
}

data class WeightEntry(val date: Date, val kilograms: Double)

@Composable
fun WeightGoalChart(entries: List<WeightEntry>) {
    // the week under the finger, or null when the user isn't dragging
    var selectedIndex by remember { mutableStateOf<Int?>(null) }
    val textMeasurer = rememberTextMeasurer()
    val dateFormat = remember { DateFormat.getDateInstance(DateFormat.MEDIUM) }
    val color = Color(0xFFAF52DE)
    val textStyle = TextStyle(color = Color.Gray, fontSize = 12.sp)
    val minKg = entries.minOf { it.kilograms }
    val kgRange = (entries.maxOf { it.kilograms } - minKg).coerceAtLeast(1.0)

    Canvas(
        Modifier
            .fillMaxSize()
            .pointerInput(entries) {
                // horizontal drags select a week; vertical drags scroll the screen
                detectHorizontalDragGestures(
                    onDragEnd = { selectedIndex = null },
                    onDragCancel = { selectedIndex = null },
                ) { change, _ ->
                    val index = (change.position.x / size.width * entries.lastIndex).roundToInt()
                    selectedIndex = index.coerceIn(0, entries.lastIndex)
                }
            }
    ) {
        val startDate = textMeasurer.measure(dateFormat.format(entries.first().date), textStyle)
        val endDate = textMeasurer.measure(dateFormat.format(entries.last().date), textStyle)
        val dateY = size.height - startDate.size.height
        val top = 24.dp.toPx() // room for the projected weight above the line
        val bottom = dateY - 8.dp.toPx()
        fun pointOf(index: Int) = Offset(
            x = size.width * index / entries.lastIndex.coerceAtLeast(1),
            y = bottom - ((entries[index].kilograms - minKg) / kgRange * (bottom - top)).toFloat(),
        )

        // the line from the current weight to the goal weight
        for (index in 1..entries.lastIndex) {
            drawLine(color, pointOf(index - 1), pointOf(index), strokeWidth = 2.dp.toPx())
        }
        // the dates of the first and the last week
        drawText(startDate, topLeft = Offset(0f, dateY))
        drawText(endDate, topLeft = Offset(size.width - endDate.size.width, dateY))

        // the selected week: a point, and the projected weight above it
        selectedIndex?.let { index ->
            val point = pointOf(index)
            drawCircle(color, radius = 5.dp.toPx(), center = point)
            val weight = String.format(Locale.getDefault(), "%.1f kg", entries[index].kilograms)
            val label = textMeasurer.measure(weight, textStyle.copy(color = color))
            val x = (point.x - label.size.width / 2)
                .coerceAtMost(size.width - label.size.width)
                .coerceAtLeast(0f)
            drawText(label, topLeft = Offset(x, point.y - label.size.height - 8.dp.toPx()))
        }
    }
}
```

</TabItem>
</Tabs>

Le plan suppose que le poids évolue de 0,5 kg par semaine. Pour utiliser un autre taux, modifiez `weeklyChange`.

## 5. Associer le graphique à l'élément personnalisé \{#match-the-chart-to-the-custom-element\}

Dans votre [résolveur global](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk), ajoutez une propriété `WeightPlanStore`. Ensuite, retournez la vue du graphique pour le Type `line_chart` et l'ID `weight_goal`. Les lignes surlignées indiquent ce qu'il faut ajouter ou modifier. Si votre application n'a pas encore de [résolveur](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) global, copiez l'intégralité du code :

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift" {4-8,11,19-23}

// the weight plan that your shared code sends before the paywall flow opens
@MainActor
final class WeightPlanStore {
    var plan: WeightPlan?
}

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let weightPlanStore: WeightPlanStore

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "line_chart" where id == "weight_goal":
            guard #available(iOS 16.0, *), let plan = weightPlanStore.plan else {
                return nil // no weight plan: show the fallback
            }
            return AnyView(WeightGoalChart(entries: plan.entries))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin" {4-7,10,15-22}

// the weight plan that your shared code sends before the paywall flow opens
class WeightPlanStore {
    var plan: WeightPlan? = null
}

class CustomElementsResolver(
    private val weightPlanStore: WeightPlanStore,
) : AdaptyCustomElementsResolver {

    override fun resolve(type: String, id: String): AdaptyCustomElementContent? =
        when (type) {
            "line_chart" -> {
                val plan = weightPlanStore.plan
                if (id == "weight_goal" && plan != null) {
                    AdaptyCustomElementContent.compose { WeightGoalChart(plan.entries) }
                } else {
                    null // no weight plan: show the fallback
                }
            }
            // the other Types of your resolver
            else -> null
        }
}
```

</TabItem>
</Tabs>

Tant que votre code partagé n'envoie pas le poids actuel et l'objectif de poids à votre code natif, le resolver ne retourne aucune vue et les utilisateurs voient le paywall de secours.

## 6. Envoyer le poids actuel et l'objectif depuis votre code partagé \{#6-send-the-current-and-goal-weight-from-your-shared-code\}

Définissez le resolver au lancement de l'application et remplissez le store depuis votre code partagé. Votre code partagé ne peut pas appeler votre code Swift ni la classe `MainApplication`. Pour remplir le store, déclarez une interface dans votre code partagé et implémentez-la dans la classe `WeightPlanStore` de chaque plateforme.

Dans `commonMain`, déclarez l'interface et un objet qui contient le store de la plateforme courante :

```kotlin showLineNumbers title="commonMain"
// the weight plan store of each platform implements this interface
interface WeightPlanReceiver {
    fun setWeights(currentWeight: Double, goalWeight: Double)
}

object WeightPlanBridge {
    // the platform code sets the receiver at app launch
    var receiver: WeightPlanReceiver? = null
}
```

Implémentez l'interface pour chaque plateforme :

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

Make `WeightPlanStore` conform to the `WeightPlanReceiver` protocol from your shared framework, such as `ComposeApp`. The highlighted lines show what to add:

```swift showLineNumbers title="Swift" {1,5,8-14}

// the weight plan that your shared code sends before the paywall flow opens
@MainActor
final class WeightPlanStore: WeightPlanReceiver {
    var plan: WeightPlan?

    // your shared code can call this method on any thread
    nonisolated func setWeights(currentWeight: Double, goalWeight: Double) {
        // the resolver reads the weight plan on the main thread
        Task { @MainActor in
            self.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
        }
    }
}
```

Dans `iOSApp.swift`, ajoutez une propriété pour le plan de poids à votre classe `AppDelegate`. Définissez le resolver et le receiver dans la méthode `application(_:didFinishLaunchingWithOptions:)`. Les lignes surlignées indiquent ce qu'il faut ajouter. Conservez le reste de la classe `AppDelegate` tel quel :

```swift showLineNumbers title="iosApp/iosApp/iOSApp.swift" {1-2,6-7,13-14}

class AppDelegate: UIResponder, UIApplicationDelegate {
    // the weight plan that your shared code sends
    let weightPlanStore = WeightPlanStore()

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
        WeightPlanBridge.shared.receiver = weightPlanStore
        // the rest of your launch code
        return true
    }
}
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

Faites implémenter l'interface `WeightPlanReceiver` par `WeightPlanStore`. Les lignes surlignées indiquent ce qu'il faut ajouter :

```kotlin showLineNumbers title="Kotlin" {2,5-9}
// the weight plan that your shared code sends before the paywall flow opens
class WeightPlanStore : WeightPlanReceiver {
    var plan: WeightPlan? = null

    // showWeightPaywall calls this method on the main thread,
    // where the resolver reads the weight plan
    override fun setWeights(currentWeight: Double, goalWeight: Double) {
        plan = WeightPlan(currentWeight, goalWeight)
    }
}
```

Dans `MainApplication.kt`, ajoutez une propriété pour le plan de poids. Définissez le resolver et le receiver dans la méthode `onCreate`. Les lignes surlignées indiquent ce qu'il faut ajouter. Laissez le reste de la classe `MainApplication` tel quel :

```kotlin showLineNumbers title="MainApplication.kt" {7-8,12-13}
package com.example.app

class MainApplication : Application() {
    // the weight plan that your shared code sends
    val weightPlanStore = WeightPlanStore()

    override fun onCreate() {
        super.onCreate()
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore))
        WeightPlanBridge.receiver = weightPlanStore
    }
}
```

</TabItem>
</Tabs>

Dans votre code partagé, envoyez le poids actuel et le poids cible au store avant l'ouverture du flow de paywall :

```kotlin showLineNumbers title="commonMain"

private val mainUiScope = MainScope()

fun showWeightPaywall(currentWeight: Double, goalWeight: Double) {
    mainUiScope.launch {
        // the native resolver builds the chart from the current and goal weight
        WeightPlanBridge.receiver?.setWeights(currentWeight, goalWeight)
        Adapty.getFlow("weight_paywall")
            .onSuccess { flow ->
                AdaptyUI.createFlowView(flow)
                    .onSuccess { view -> view.present() }
                    .onError { error ->
                        // handle the error
                    }
            }
            .onError { error ->
                // handle the error
            }
    }
}
```

## 7. Tester sur un appareil \{#7-test-on-a-device\}

Le Flow & Paywall Builder ne peut pas exécuter le code de votre application, donc son canvas affiche uniquement le paywall de secours. Pour prévisualiser le graphique :

1. [Publiez les deux flows](builder-save-publish). Pour voir les dernières versions publiées plutôt que les versions en cache, enregistrez l'appareil en tant qu'[appareil de test](test-devices).
2. Lancez un build de votre application incluant le resolver. Sur iOS, utilisez un appareil sous iOS 17 ou version ultérieure. Complétez le flow d'onboarding avec un poids actuel et un poids cible. Vérifiez que la ligne du graphique commence au poids actuel et se termine au poids cible.
3. Faites glisser votre doigt sur le graphique et vérifiez que le poids projeté pour la semaine sous votre doigt s'affiche au-dessus de la ligne.

Pour tester le fallback, ne retournez aucune vue pour le type `line_chart`, puis ouvrez à nouveau le flow du paywall.

Pour comprendre pourquoi le paywall de secours s'affiche à la place du graphique, suivez les instructions de la section [Tester sur un appareil](kmp-flow-custom-elements#test-on-a-device) du guide Kotlin Multiplatform.