---
title: "Показать интерактивный график цели по весу в пейволе"
description: "Отображайте прогнозируемый вес каждого пользователя в виде графика в пейволе флоу. Пользователи могут перетаскивать ползунок по графику, чтобы увидеть вес для любой недели."
---

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

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

Следуйте этому рецепту, чтобы отображать прогнозируемый вес пользователя в виде графика в пейволе флоу. Пользователь вводит текущий и целевой вес в онбординге. Ваше приложение собирает оба значения. График показывает еженедельный прогресс, которого пользователь может ожидать с вашим приложением — от одного значения к другому. Приложение отображает график как нативный вид в [кастомном элементе](flow-custom-elements). На iOS вид использует Swift Charts. На Android вид рисует график без библиотеки.

## Прежде чем начать \{#before-you-start\}

- Обновите приложение до Adapty Kotlin Multiplatform SDK 4.4.0-beta.1 или новее. Более ранние версии SDK показывают [резервный контент](flow-custom-elements#set-fallback-content) для каждого кастомного элемента.
- Настройте приложение для [получения](kmp-get-pb-paywalls) и [отображения](kmp-present-paywalls) флоу.
- Настройте нативный код приложения для кастомных элементов, как описано в [гайде по Kotlin Multiplatform](kmp-flow-custom-elements#before-you-start).
- На iOS перетаскивание по графику требует iOS 17 или новее. На iOS 16 пользователи видят линию, но не могут перетаскивать её.
- На Android [настройте Android-проект](kmp-flow-custom-elements#set-up-your-android-project), включая Jetpack Compose. График в этом примере является composable-компонентом. Если приложение не использует Compose Multiplatform, добавьте Compose Foundation в зависимости `androidMain` из `androidx.compose.foundation:foundation` без указания версии. Версию задаёт Compose BOM из `io.adapty:android-ui`.

Создайте два отдельных флоу — один для онбординга, другой для пейвола. Добавьте каждый в [плейсмент](placements). Код в этом рецепте получает флоу пейвола из плейсмента с ID `weight_paywall`.

## 1. Запросите текущий и целевой вес в онбординге \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

В Flow & Paywall Builder добавьте два поля ввода [**Number**](builder-inputs-and-forms) в флоу онбординга:

- Одно для текущего веса в килограммах с **Element ID** `weight`.
- Одно для целевого веса в килограммах с **Element ID** `goal_weight`.

Чтобы приложение считывало вес одинаково во всех локалях, выберите **Integer** в выпадающем списке **Format** для обоих полей. Поле отправляет значение в приложение как текст ровно в том виде, в каком пользователь его ввёл. Код в этом рецепте по-разному обработает «70.5» и «70,5». Целые числа не содержат разделителя дробной части.

Чтобы приложение гарантированно получило оба значения, завершите флоу онбординга экраном без полей ввода. На этом экране добавьте кнопку с действием [**Close flow**](onboarding-actions#close-flow). Поля ввода отправляют свои значения при потере фокуса или при переходе пользователя на другой экран.

## 2. Добавьте пользовательский элемент на экран пейвола \{#2-add-the-custom-element-to-the-paywall-screen\}

В флоу пейвола [добавьте кастомный элемент](flow-custom-elements#add-and-configure) на экран и настройте его для графика:

- **Type**: `line_chart`.
- **ID**: `weight_goal`.
- **Height**: Оставьте высоту по умолчанию **Fixed**. График заполнит кастомный элемент.

Не помещайте кастомный элемент в контейнеры, реагирующие на касание, например в карусель, — чтобы только график реагировал на перетаскивание по нему.

Внутри кастомного элемента добавьте [**Image**](custom-media#image) с примером графика веса. Пользователи увидят его как [резервный контент](flow-custom-elements#set-fallback-content), если версия вашего приложения не отображает график.

## 3. Сохраните текущий и целевой вес в приложении \{#3-save-the-current-and-goal-weight-in-your-app\}

Собирайте текущий и целевой вес из событий `flow_user_input` онбординг-флоу, как описано в разделе [Обработка данных из флоу](kmp-flow-input). Чтобы определить момент, когда пользователь дошёл до последнего экрана, отслеживайте событие `flow_screen_showed` с полем `is_last_screen`, равным `true`. Когда онбординг-флоу закроется после этого экрана, передайте текущий и целевой вес в `showWeightPaywall` — функцию, которая [открывает пейвол-флоу с графиком](#6-send-the-current-and-goal-weight-from-your-shared-code).

Один обозреватель получает события обоих флоу. Зарегистрируйте его с помощью `AdaptyUI.setFlowsEventsObserver` до того, как покажете онбординг-флоу. Новый обозреватель заменяет предыдущий: если в вашем приложении уже зарегистрирован обозреватель, добавьте в него код из `WeightFlowsObserver`. Функция `showWeightPaywall` описана на [шаге 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. Создайте представление графика \{#create-the-chart-view\}

Создайте модель плана снижения веса и представление с графиком. В плане — одна запись на неделю: от текущего веса до целевого. Когда пользователь перетаскивает палец по графику, представление отмечает неделю в точке касания и показывает прогнозируемый вес для этой недели:

<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))
    }
}
```

Перетаскивание по графику требует iOS 17 или новее. На iOS 16 пользователи видят линию, но не могут перемещаться по ней.

</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>

План предполагает изменение веса на 0,5 кг в неделю. Чтобы использовать другой темп, отредактируйте `weeklyChange`.

## 5. Привяжите график к пользовательскому элементу \{#match-the-chart-to-the-custom-element\}

В вашем [общем резолвере приложения](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk) добавьте свойство `WeightPlanStore`. Затем верните представление графика для типа `line_chart` и ID `weight_goal`. Выделенные строки показывают, что нужно добавить или изменить. Если в вашем приложении ещё нет общего [резолвера](kmp-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views), скопируйте весь код целиком:

<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>

Пока ваш общий код не передаёт текущий и целевой вес в нативный код, резолвер не возвращает представление, и пользователи видят резервный пейвол.

## 6. Отправьте текущий и целевой вес из общего кода \{#6-send-the-current-and-goal-weight-from-your-shared-code\}

Установите резолвер при запуске приложения и наполните стор из общего кода. Общий код не может вызывать ваш Swift-код или класс `MainApplication`. Чтобы наполнить стор, объявите интерфейс в общем коде и реализуйте его в классе `WeightPlanStore` каждой платформы.

В `commonMain` объявите интерфейс и объект, который хранит стор текущей платформы:

```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
}
```

Реализуйте интерфейс для каждой платформы:

<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)
        }
    }
}
```

В `iOSApp.swift` добавьте свойство для плана весов в класс `AppDelegate`. Установите resolver и receiver в методе `application(_:didFinishLaunchingWithOptions:)`. Выделенные строки показывают, что нужно добавить. Остальную часть класса `AppDelegate` оставьте без изменений:

```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)">

Добавьте в `WeightPlanStore` реализацию интерфейса `WeightPlanReceiver`. Выделенные строки показывают, что нужно добавить:

```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)
    }
}
```

В `MainApplication.kt` добавьте свойство для плана по весу. Задайте резолвер и получатель в методе `onCreate`. Выделенные строки показывают, что нужно добавить. Остальную часть класса `MainApplication` оставьте без изменений:

```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>

В своём коде отправьте текущий и целевой вес в стор до того, как откроется флоу пейвола:

```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. Протестируйте на устройстве \{#7-test-on-a-device\}

Paywall Builder не может запустить код вашего приложения, поэтому его холст показывает только резервный вариант. Чтобы просмотреть график:

1. [Опубликуйте оба флоу](builder-save-publish). Чтобы видеть последние опубликованные версии вместо кэшированных, зарегистрируйте устройство как [тестовое](test-devices).
2. Запустите сборку приложения с резолвером. На iOS используйте устройство с iOS 17 или новее. Пройдите онбординг, указав текущий и целевой вес. Убедитесь, что линия графика начинается с текущего веса и заканчивается на целевом.
3. Проведите пальцем по графику и убедитесь, что прогнозируемый вес за неделю под пальцем отображается над линией.

Чтобы проверить резервный вариант, не возвращайте никакого представления для типа `line_chart` и снова откройте флоу с пейволом.

Чтобы разобраться, почему вместо графика отображается резервный вариант, следуйте инструкциям из раздела [Тестирование на устройстве](kmp-flow-custom-elements#test-on-a-device) в руководстве по Kotlin Multiplatform.