---
title: "ペイウォールにインタラクティブな体重目標チャートを表示する"
description: "ペイウォールフローで各ユーザーの予測体重をチャートとして表示します。ユーザーはチャート上をドラッグして任意の週の体重を確認できます。"
---

> For the complete documentation index, see [llms.txt](https://adapty.io/docs/ja/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 では、Jetpack Compose を含む[Android プロジェクトのセットアップ](kmp-flow-custom-elements#set-up-your-android-project)を行ってください。このレシピのチャートはコンポーザブルです。アプリが Compose Multiplatform を使用していない場合は、`androidMain` の依存関係に `androidx.compose.foundation:foundation` からバージョン指定なしで Compose Foundation を追加してください。バージョンは `io.adapty:android-ui` の Compose BOM によって設定されます。

2つの別々のフローを作成します。1つはオンボーディング用、もう1つはペイウォール用です。それぞれを[プレースメント](placements)に追加してください。このレシピのコードは、ID `weight_paywall` のプレースメントからペイウォールフローを取得します。

## 1. オンボーディングフローで現在の体重と目標体重を入力してもらう \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

フロー & ペイウォールビルダーで、オンボーディングフローに2つの[**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)を追加します。お使いのアプリのバージョンがチャートを表示できない場合、ユーザーにはこれが[フォールバック](flow-custom-elements#set-fallback-content)として表示されます。

## 3. アプリに現在の体重と目標体重を保存する \{#3-save-the-current-and-goal-weight-in-your-app\}

オンボーディングフローの `flow_user_input` イベントから現在の体重と目標体重を収集します。方法は[フローからのデータ処理](kmp-flow-input)を参照してください。ユーザーが最後の画面に到達したことを確認するには、`is_last_screen` が `true` に設定された `flow_screen_showed` イベントを監視します。その画面の後にオンボーディングフローが閉じたら、現在の体重と目標体重を `showWeightPaywall`（[チャート付きのペイウォールフローを開く](#6-send-the-current-and-goal-weight-from-your-shared-code)関数）に渡します。

1つのオブザーバーで、両方のフローのイベントを受け取ります。オンボーディングフローを表示する前に、`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\}

体重プランのモデルと、チャートを表示するビューを作成します。このプランは現在の体重から目標体重まで、週ごとに1つのエントリを持ちます。ユーザーがチャート上をドラッグすると、タッチした位置の週がマークされ、その週の予測体重が表示されます。

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

このプランでは、体重が1週間に0.5 kgずつ変化することを前提としています。別の変化率を使用するには、`weeklyChange` を編集してください。

## 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\}

リゾルバをアプリ起動時に設定し、共有コードからストアにデータを入力します。共有コードは 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` クラスに、ウェイトプランのプロパティを追加します。`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\}

フロービルダー・ペイウォールビルダーはアプリのコードを実行できないため、キャンバスにはフォールバックのみが表示されます。チャートをプレビューするには:

1. [両方のフローを公開する](builder-save-publish)。キャッシュではなく最新の公開バージョンを確認するには、デバイスを[テストデバイス](test-devices)として登録してください。
2. リゾルバーを含むアプリのビルドを実行します。iOS の場合は iOS 17 以降のデバイスを使用してください。現在の体重と目標体重を入力してオンボーディングフローを完了します。チャートの線が現在の体重から始まり、目標体重で終わることを確認してください。
3. チャート上をドラッグして、指の下の週の予測体重が線の上に表示されることを確認してください。

フォールバックをテストするには、`line_chart` タイプに対してビューを返さないようにし、ペイウォールフローを再度開いてください。

チャートの代わりにフォールバックが表示される理由を確認するには、Kotlin Multiplatform ガイドの[デバイスでテストする](kmp-flow-custom-elements#test-on-a-device)セクションの手順に従ってください。