---
title: "Mostrar un gráfico interactivo de objetivos de peso en un paywall"
description: "Muestra el peso proyectado de cada usuario como un gráfico en un flow de paywall. Los usuarios deslizan el gráfico para ver el peso de cualquier semana."
---

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

Sigue esta receta para mostrar el peso proyectado de cada usuario como un gráfico en un flow de paywall. El usuario introduce su peso actual y su peso objetivo en un flow de onboarding. Tu app recoge ambos valores. El gráfico muestra el progreso semanal que el usuario puede esperar con tu app, desde un valor hasta el otro. Tu app renderiza el gráfico como una vista nativa en un [elemento personalizado](flow-custom-elements). En iOS, la vista usa Swift Charts. En Android, la vista dibuja el gráfico sin ninguna librería de gráficos.

## Antes de empezar \{#before-you-start\}

- Actualiza tu app al SDK de Adapty para React Native 4.4 o posterior. Las versiones anteriores del SDK muestran el [contenido de respaldo](flow-custom-elements#set-fallback-content) para cada elemento personalizado.
- Configura tu app para [obtener](react-native-get-pb-paywalls) y [mostrar](react-native-present-paywalls) flows.
- Configura el código nativo de tu app para los elementos personalizados, como se indica en la [guía de React Native](react-native-flow-custom-elements#before-you-start).
- En iOS, el arrastre a lo largo del gráfico requiere iOS 17 o posterior. En iOS 16, los usuarios ven la línea, pero no pueden arrastrar a lo largo de ella.
- En Android, [configura Jetpack Compose](react-native-flow-custom-elements#set-up-jetpack-compose) en el módulo de tu app. El gráfico en esta receta es un composable. Añade Compose Foundation a tu app con Gradle, desde `androidx.compose.foundation:foundation`.

Crea dos flows separados — uno para el onboarding y otro para el paywall. Añade cada uno a un [placement](placements). El código de esta receta obtiene el flow del paywall desde el placement con el ID `weight_paywall`.

## 1. Solicitar el peso actual y el objetivo en el onboarding \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

En el Flow & Paywall Builder, añade dos entradas de tipo [**Number**](builder-inputs-and-forms) al flow de onboarding:

- Una para el peso actual en kilogramos, con el **Element ID** `weight`.
- Una para el peso objetivo en kilogramos, con el **Element ID** `goal_weight`.

Para que tu app lea los pesos de la misma forma en cualquier idioma, selecciona **Integer** en el desplegable **Format** de ambas entradas. Una entrada envía su valor a tu app como texto, exactamente como lo escribe el usuario. El código de esta receta interpreta "70.5" y "70,5" de forma diferente. Los números enteros no tienen separador decimal.

Para asegurarte de que tu app recibe ambos valores, termina el flow de onboarding con una pantalla que no tenga entradas. En esa pantalla, añade un botón con la acción [**Close flow**](onboarding-actions#close-flow). Las entradas envían sus valores cuando pierden el foco o cuando el usuario pasa a otra pantalla.

## 2. Añade el elemento personalizado a la pantalla de paywall \{#2-add-the-custom-element-to-the-paywall-screen\}

En el flow del paywall, [añade un elemento personalizado](flow-custom-elements#add-and-configure) a una pantalla y configúralo para el gráfico:

- **Type**: `line_chart`.
- **ID**: `weight_goal`.
- **Height**: Mantén la altura **Fixed** predeterminada. El gráfico ocupa todo el elemento personalizado.

Mantén el elemento personalizado fuera de contenedores que respondan al toque, como un carrusel, para que solo el gráfico responda al arrastre sobre él.

Dentro del elemento personalizado, añade una [**Image**](custom-media#image) con un gráfico de peso de muestra. Los usuarios la verán como [respaldo](flow-custom-elements#set-fallback-content) cuando la versión de tu app no muestre el gráfico.

## 3. Guarda el peso actual y el objetivo en tu app \{#3-save-the-current-and-goal-weight-in-your-app\}

Recoge el peso actual y el objetivo a partir de los eventos `flow_user_input` del flow de onboarding, tal como se describe en [Procesar datos de flows](react-native-flow-input). Para saber que el usuario llegó a la última pantalla, escucha un evento `flow_screen_showed` con `is_last_screen` igual a `true`. Cuando el flow de onboarding se cierre tras esa pantalla, pasa ambos pesos a `showWeightPaywall`, la función que [abre el flow del paywall con el gráfico](#6-send-the-weights-from-your-javascript-code).

La siguiente función devuelve los handlers `onAnalytics` y `onDisappeared` del flow de onboarding:

```typescript showLineNumbers title="weightOnboardingHandlers.ts"

// the event handlers of the onboarding flow view
export function weightOnboardingHandlers(): Partial<FlowEventHandlers> {
  const enteredWeights: Record<string, string> = {};
  let reachedLastScreen = false;

  return {
    onAnalytics(name, params) {
      if (name === 'flow_screen_showed' && params.is_last_screen === true) {
        reachedLastScreen = true;
      } else if (
        name === 'flow_user_input' &&
        typeof params.element_id === 'string' &&
        typeof params.value === 'string'
      ) {
        enteredWeights[params.element_id] = params.value;
      }
      return false; // keep the flow open
    },
    onDisappeared() {
      // number inputs send their values as strings
      const currentWeight = Number.parseFloat(enteredWeights.weight ?? '');
      const goalWeight = Number.parseFloat(enteredWeights.goal_weight ?? '');
      if (reachedLastScreen && !Number.isNaN(currentWeight) && !Number.isNaN(goalWeight)) {
        showWeightPaywall(currentWeight, goalWeight);
      }
      return false;
    },
  };
}
```

Antes de presentar el flow de onboarding, pasa los handlers a su vista:

```typescript showLineNumbers title="React Native"
const view = await createFlowView(flow);
view.setEventHandlers(weightOnboardingHandlers());
await view.present();
```

Si tu app ya define `onAnalytics` o `onDisappeared` para el flow de onboarding, añade el código de `weightOnboardingHandlers` a tus handlers. Cada handler que pases a `setEventHandlers` reemplaza cualquier handler anterior que tenga el mismo nombre.

## 4. Crea la vista del gráfico \{#create-the-chart-view\}

Crea un modelo de plan de peso y una vista con el gráfico. El plan tiene una entrada por semana, desde el peso actual hasta el peso objetivo. Cuando el usuario arrastra por el gráfico, la vista marca la semana en el punto de toque y muestra el peso proyectado para esa semana:

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

El arrastre a lo largo del gráfico requiere iOS 17 o posterior. En iOS 16, los usuarios ven la línea, pero no pueden arrastrar a lo largo de ella.

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

El plan asume que el peso cambia 0,5 kg por semana. Para usar otra tasa, edita `weeklyChange`.

## 5. Asocia el gráfico al elemento personalizado \{#match-the-chart-to-the-custom-element\}

En tu [resolver global](react-native-flow-custom-elements#pass-the-resolver-to-the-sdk), añade una propiedad `WeightPlanStore`. Luego devuelve la vista del gráfico para el Type `line_chart` y el ID `weight_goal`. Las líneas resaltadas muestran qué añadir o cambiar. Si tu app aún no tiene un [resolver](react-native-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views) global, copia el código completo:

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

Hasta que tu código JavaScript envíe los pesos al código nativo, el resolver no devuelve ninguna vista y los usuarios ven el paywall de respaldo.

## 6. Envía los pesos desde tu código JavaScript \{#6-send-the-weights-from-your-javascript-code\}

Configura el resolver al iniciar la app y rellena el store desde tu código JavaScript mediante un [Turbo Native Module](https://reactnative.dev/docs/turbo-native-modules-introduction). El módulo tiene una especificación JavaScript y una implementación para cada plataforma.

En una carpeta `specs` en la raíz de tu proyecto, crea la especificación del módulo:

```typescript showLineNumbers title="specs/NativeWeightPlanStore.ts"

export interface Spec extends TurboModule {
  setWeights(currentWeight: number, goalWeight: number): void;
}

export default TurboModuleRegistry.getEnforcing<Spec>('NativeWeightPlanStore');
```

Para generar el código nativo de la spec, añade `codegenConfig` a `package.json`. Reemplaza `com.example.app` con el nombre del paquete de tu app de Android, en `package.json` y en la implementación Kotlin del módulo. Si `package.json` ya tiene `codegenConfig`, solo añade `NativeWeightPlanStore` al objeto `modulesProvider`:

```json showLineNumbers title="package.json"
"codegenConfig": {
  "name": "AppSpecs",
  "type": "modules",
  "jsSrcsDir": "specs",
  "android": {
    "javaPackageName": "com.example.app.specs"
  },
  "ios": {
    "modulesProvider": {
      "NativeWeightPlanStore": "RCTNativeWeightPlanStore"
    }
  }
}
```

Implementa el módulo para cada plataforma:

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

En el target de tu app en Xcode, crea un módulo Objective-C++. Envía los pesos a tu código Swift a través de `NotificationCenter`:

```objectivec showLineNumbers title="RCTNativeWeightPlanStore.h"
#import <AppSpecs/AppSpecs.h>

@interface RCTNativeWeightPlanStore : NSObject <NativeWeightPlanStoreSpec>
@end
```

```objectivec showLineNumbers title="RCTNativeWeightPlanStore.mm"
#import "RCTNativeWeightPlanStore.h"

@implementation RCTNativeWeightPlanStore

+ (NSString *)moduleName {
  return @"NativeWeightPlanStore";
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params {
  return std::make_shared<facebook::react::NativeWeightPlanStoreSpecJSI>(params);
}

- (void)setWeights:(double)currentWeight goalWeight:(double)goalWeight {
  // the AppDelegate updates the weight plan when it receives this notification
  [[NSNotificationCenter defaultCenter] postNotificationName:@"WeightsDidChange"
                                                      object:nil
                                                    userInfo:@{@"current": @(currentWeight),
                                                               @"goal": @(goalWeight)}];
}

@end
```

En `AppDelegate.swift`, añade una propiedad para el plan de peso. En el método `application(_:didFinishLaunchingWithOptions:)`, establece el resolver y observa `NotificationCenter` para actualizar el plan de peso con cada par de pesos. Las líneas resaltadas muestran qué añadir. Deja el resto de la clase `AppDelegate` tal como está:

```swift showLineNumbers title="ios/YourApp/AppDelegate.swift" {1,6-7,13-26}

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

  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
  ) -> Bool {
    AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
    // the weights that your JavaScript code sends through the native module
    NotificationCenter.default.addObserver(
      forName: Notification.Name("WeightsDidChange"),
      object: nil,
      queue: .main
    ) { [weightPlanStore] notification in
      guard let currentWeight = notification.userInfo?["current"] as? Double,
            let goalWeight = notification.userInfo?["goal"] as? Double
      else { return }
      MainActor.assumeIsolated {
        weightPlanStore.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
      }
    }
    // the rest of your launch code
    return true
  }
}
```

Para generar el código nativo de la especificación, ejecuta `pod install` en la carpeta `ios`.

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

Crea el módulo y un paquete que lo registre en React Native:

```kotlin showLineNumbers title="NativeWeightPlanStoreModule.kt"
package com.example.app

class NativeWeightPlanStoreModule(reactContext: ReactApplicationContext) :
    NativeWeightPlanStoreSpec(reactContext) {

    override fun getName() = NAME

    override fun setWeights(currentWeight: Double, goalWeight: Double) {
        val app = reactApplicationContext.applicationContext as MainApplication
        // the resolver reads the weight plan on the main thread
        UiThreadUtil.runOnUiThread {
            app.weightPlanStore.plan = WeightPlan(currentWeight, goalWeight)
        }
    }

    companion object {
        const val NAME = "NativeWeightPlanStore"
    }
}
```

```kotlin showLineNumbers title="NativeWeightPlanStorePackage.kt"

class NativeWeightPlanStorePackage : BaseReactPackage() {
    override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
        if (name == NativeWeightPlanStoreModule.NAME) NativeWeightPlanStoreModule(reactContext) else null

    override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
        mapOf(
            NativeWeightPlanStoreModule.NAME to ReactModuleInfo(
                name = NativeWeightPlanStoreModule.NAME,
                className = NativeWeightPlanStoreModule.NAME,
                canOverrideExistingModule = false,
                needsEagerInit = false,
                isCxxModule = false,
                isTurboModule = true,
            )
        )
    }
}
```

En `MainApplication.kt`, añade una propiedad para el plan de peso y establece el resolver en el método `onCreate`. Las líneas resaltadas muestran qué añadir. Mantén el resto de la clase `MainApplication` tal como está:

```kotlin showLineNumbers title="MainApplication.kt" {1,4-5,11}

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

  // the other members of your MainApplication class

  override fun onCreate() {
    super.onCreate()
    AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore))
    // the rest of your onCreate code
  }
}
```

En `MainApplication.kt`, añade `NativeWeightPlanStorePackage` a la lista de paquetes:

```kotlin showLineNumbers title="MainApplication.kt" {2}
PackageList(this).packages.apply {
  add(NativeWeightPlanStorePackage())
}
```

</TabItem>
</Tabs>

En tu código JavaScript, envía los pesos al store antes de que se abra el flow del paywall:

```typescript showLineNumbers title="showWeightPaywall.ts"

export async function showWeightPaywall(currentWeight: number, goalWeight: number) {
  try {
    // the native resolver builds the chart from these weights
    NativeWeightPlanStore.setWeights(currentWeight, goalWeight);
    const flow = await adapty.getFlow('weight_paywall');
    const view = await createFlowView(flow);
    await view.present();
  } catch (error) {
    // handle the error
  }
}
```

## 7. Prueba en un dispositivo \{#7-test-on-a-device\}

El Flow & Paywall Builder no puede ejecutar el código de tu aplicación, por lo que el canvas solo muestra el respaldo. Para previsualizar el gráfico:

1. [Publica ambos flows](builder-save-publish). Para ver las últimas versiones publicadas en lugar de las almacenadas en caché, registra el dispositivo como [dispositivo de prueba](test-devices).
2. Ejecuta una compilación de tu app que incluya el resolver. En iOS, usa un dispositivo con iOS 17 o posterior. Completa el onboarding con un peso actual y un peso objetivo. Verifica que la línea del gráfico empiece en el peso actual y termine en el peso objetivo.
3. Arrastra a lo largo del gráfico y verifica que el peso proyectado para la semana bajo tu dedo aparezca encima de la línea.

Para probar el fallback, devuelve ninguna vista para el tipo `line_chart` y abre el flow del paywall de nuevo.

Para averiguar por qué aparece el fallback en lugar del gráfico, sigue las instrucciones de la sección [Probar en un dispositivo](react-native-flow-custom-elements#test-on-a-device) de la guía de React Native.