---
title: "在付费墙中显示交互式体重目标图表"
description: "在付费墙流程中以图表形式展示每位用户的预计体重变化，用户可拖动图表查看任意周的体重数据。"
---

> For the complete documentation index, see [llms.txt](https://adapty.io/docs/zh/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。此方案中的数据图表是一个可组合项。如果您的应用未使用 Compose Multiplatform，请将 Compose Foundation 添加到 `androidMain` 依赖项中，来源为 `androidx.compose.foundation:foundation`，无需指定版本。版本由 `io.adapty:android-ui` 的 Compose BOM 统一管理。

创建两个独立的流程——一个用于用户引导，一个用于付费墙。将每个流程添加到对应的[版位](placements)。本示例代码从 ID 为 `weight_paywall` 的版位获取付费墙流程。

## 1. 在用户引导流程中询问当前体重和目标体重 \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

在流程与付费墙编辑工具中，向用户引导流程添加两个 [**Number** 输入框](builder-inputs-and-forms)：

- 一个用于输入当前体重（千克），**Element ID** 设为 `weight`。
- 一个用于输入目标体重（千克），**Element ID** 设为 `goal_weight`。

为确保您的应用在所有语言环境下以统一方式读取体重值，请在两个输入框的 **Format** 下拉菜单中选择 **Integer**。输入框会将用户输入的内容原样以文本形式发送给应用。本示例代码对 "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)。当用户所使用的 app 版本无法显示图表时，该图片将作为[备用内容](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 kg。如需使用其他变化速率，请修改 `weeklyChange`。

## 5. 将数据图表与自定义元素匹配 \{#5-match-the-chart-to-the-custom-element\}

在你的[全局解析器](kmp-flow-custom-elements#pass-the-resolver-to-the-sdk)中，添加一个 `WeightPlanStore` 属性。然后为 `line_chart` 类型和 `weight_goal` ID 返回图表视图。高亮行显示了需要添加或修改的内容。如果你的应用还没有全局[解析器](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\}

在应用启动时设置解析器，并从共享代码中填充 store。共享代码无法调用你的 Swift 代码或 `MainApplication` 类。要填充 store，需在共享代码中声明一个接口，然后在各平台的 `WeightPlanStore` 类中实现它。

在 `commonMain` 中，声明该接口以及一个持有当前平台 store 的对象：

```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` 类添加一个体重计划属性。在 `application(_:didFinishLaunchingWithOptions:)` 方法中设置 resolver 和 receiver。高亮行显示了需要添加的内容。保持 `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>

在您共享的代码中，在付费墙流程打开之前，将当前体重和目标体重发送到 store：

```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. 在设备上测试 \{#test-on-a-device\}

流程与付费墙编辑工具无法运行你的应用代码，因此其画布只会显示备用内容。要预览数据图表：

1. [发布这两个流程](builder-save-publish)。若要查看最新发布版本而非缓存版本，请将设备注册为[测试设备](test-devices)。
2. 运行包含 resolver 的应用构建版本。在 iOS 上，请使用 iOS 17 或更高版本的设备。完成用户引导流程，输入当前体重和目标体重。验证数据图表的折线是否从当前体重开始，到目标体重结束。
3. 在数据图表上拖动，验证手指所在周的预测体重是否显示在折线上方。

要测试备用方案，请对 `line_chart` 类型不返回任何视图，然后重新打开付费墙流程。

要了解为什么备用方案会代替数据图表出现，请参阅 Kotlin Multiplatform 指南中的[在设备上测试](kmp-flow-custom-elements#test-on-a-device)部分。