class WeightFlowsObserver extends AdaptyUIFlowsEventsObserver { final _enteredWeights = <String, String>{}; var _reachedLastScreen = false; @override void flowViewDidReceiveAnalyticEvent( AdaptyUIFlowView view, String name, Map<String, dynamic> params, ) { if (name == 'flow_screen_showed' && params['is_last_screen'] == true) { _reachedLastScreen = true; return; } final elementId = params['element_id']; final value = params['value']; if (name == 'flow_user_input' && elementId is String && value is String) { _enteredWeights[elementId] = value; } } @override void flowViewDidDisappear(AdaptyUIFlowView view) { // This observer receives events from both flows. Reset the entered // weights whenever a flow disappears, so that the paywall doesn't open // again when the user closes it. final weights = Map.of(_enteredWeights); final finished = _reachedLastScreen; _enteredWeights.clear(); _reachedLastScreen = false; // Number inputs send their values as strings final currentWeight = double.tryParse(weights['weight'] ?? ''); final goalWeight = double.tryParse(weights['goal_weight'] ?? ''); if (!finished || currentWeight == null || goalWeight == null) return; showWeightPaywall(currentWeight, goalWeight); // defined in step 6 } @override void flowViewDidFinishPurchase( AdaptyUIFlowView view, AdaptyPaywallProduct product, AdaptyPurchaseResult purchaseResult, ) { // handle the purchase result } @override void flowViewDidFinishRestore(AdaptyUIFlowView view, AdaptyProfile profile) { // check the access level of the user } @override void flowViewDidReceiveError(AdaptyUIFlowView view, AdaptyError error) { view.dismiss().catchError((_) {}); }}// call at app launch, before you present the onboarding flowvoid registerWeightFlowsObserver() { AdaptyUI().setFlowsEventsObserver(WeightFlowsObserver());}
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)@Composablefun 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())) } }}
アプリ全体のリゾルバーに WeightPlanStore プロパティを追加します。次に、line_chart タイプと weight_goal ID に対してチャートビューを返します。ハイライトされた行が追加または変更が必要な箇所です。アプリにまだリゾルバーがない場合は、コード全体をコピーしてください:
// the weight plan that your Dart code sends before the paywall flow opens@MainActorfinal 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 } }}
// the weight plan that your Dart code sends before the paywall flow opensclass 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 }}