按照此方案,在付费墙流程中以数据图表形式展示每位用户的预计体重变化。用户在用户引导流程中输入当前体重和目标体重,你的应用收集这两个值。数据图表显示用户使用你的应用后每周可预期的进展,从初始值到目标值。你的应用以原生视图的形式在自定义元素中渲染数据图表。在 iOS 上,该视图使用 Swift Charts;在 Android 上,该视图无需图表库即可绘制数据图表。
开始之前
- 将您的应用更新至 Adapty Flutter SDK 4.4 或更高版本。早期 SDK 版本会为每个自定义元素显示备用内容。
- 设置您的应用以获取和展示流程。
- 按照 Flutter 指南为自定义元素设置应用的原生代码。
- 在 iOS 上,沿数据图表拖动需要 iOS 17 或更高版本。在 iOS 16 上,用户可以看到折线,但无法沿其拖动。
- 在 Android 上,在您的应用模块中设置 Jetpack Compose。本示例中的数据图表是一个 composable 组件。通过 Gradle 将 Compose Foundation 添加到您的应用,依赖为
androidx.compose.foundation:foundation。
创建两个独立的流程——一个用于用户引导,一个用于付费墙。将每个流程添加到对应的版位。本示例代码从 ID 为 weight_paywall 的版位获取付费墙流程。
1. 在用户引导流程中询问当前体重和目标体重
在流程与付费墙编辑工具中,向用户引导流程添加两个 Number 输入框:
- 一个用于输入当前体重(千克),Element ID 设为
weight。
- 一个用于输入目标体重(千克),Element ID 设为
goal_weight。
为确保您的应用在所有语言环境下以统一方式读取体重值,请在两个输入框的 Format 下拉菜单中选择 Integer。输入框会将用户输入的内容原样以文本形式发送给应用。本示例代码对 “70.5” 和 “70,5” 的处理方式不同,而整数没有小数分隔符。
为确保应用能接收到两个值,请在用户引导流程的末尾添加一个不包含任何输入框的屏幕。在该屏幕上添加一个按钮,并为其配置 Close flow 操作。输入框会在失去焦点或用户切换到另一个屏幕时发送其值。
2. 将自定义元素添加到付费墙页面
在付费墙流程中,向某个屏幕添加自定义元素,并为数据图表进行配置:
- Type:
line_chart。
- ID:
weight_goal。
- Height:保持默认的 Fixed 高度。图表将填满整个自定义元素。
请将自定义元素放在不响应触摸的容器之外(如轮播图),以确保只有图表响应拖动操作。
在自定义元素内部,添加一个包含示例体重图表的Image。当用户所使用的 app 版本无法显示图表时,该图片将作为备用内容展示。
3. 在应用中保存当前体重和目标体重
从用户引导流程的 flow_user_input 事件中收集当前体重和目标体重,具体方式参见处理流程中的数据。要判断用户是否到达最后一屏,可监听 flow_screen_showed 事件,当其 is_last_screen 值为 true 时即表示已到达最后一屏。在该屏关闭用户引导流程后,将两个体重值传入 showWeightPaywall——即携带数据图表打开付费墙流程的函数。
一个观察者会接收两个流程的所有事件。在展示用户引导流程之前,请通过 AdaptyUI().setFlowsEventsObserver 注册该观察者。末尾的三个方法在每个观察者中都是必须的。关于如何处理购买、恢复和错误,请参阅处理流程与付费墙事件。showWeightPaywall 函数来自第 6 步。
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 flow
void registerWeightFlowsObserver() {
AdaptyUI().setFlowsEventsObserver(WeightFlowsObserver());
}
4. 创建数据图表视图
创建一个体重计划的模型和带有数据图表的视图。该计划每周记录一条数据,从当前体重到目标体重。当用户在数据图表上拖动时,视图会标记触摸点对应的周次,并显示该周的预计体重:
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 上,用户可以看到折线,但无法沿其拖动。
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()))
}
}
}
该方案假设每周体重变化为 0.5 kg。如需使用其他变化速率,请修改 weeklyChange。
5. 将数据图表与自定义元素关联
在你的全局解析器中,添加一个 WeightPlanStore 属性。然后为 line_chart 类型和 weight_goal ID 返回对应的图表视图。高亮行显示了需要添加或修改的内容。如果你的应用还没有全局解析器,可以直接复制完整代码:
// the weight plan that your Dart 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
}
}
}
// the weight plan that your Dart 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
}
}
在您的 Dart 代码将权重发送到原生代码之前,解析器不会返回任何视图,用户将看到备用付费墙。
6. 在 Dart 代码中发送权重
在应用启动时设置解析器,并通过 平台通道 从 Dart 代码填充数据:
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
// the weight plan that your Dart code sends
let weightPlanStore = WeightPlanStore()
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
let weightChannel = FlutterMethodChannel(
name: "custom_elements/weight_plan",
binaryMessenger: engineBridge.applicationRegistrar.messenger()
)
weightChannel.setMethodCallHandler { [weightPlanStore] call, result in
guard call.method == "setWeights",
let weights = call.arguments as? [String: Double],
let currentWeight = weights["current"],
let goalWeight = weights["goal"]
else {
return result(FlutterMethodNotImplemented)
}
// the channel calls this handler on the main thread
MainActor.assumeIsolated {
weightPlanStore.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
}
result(nil)
}
}
}
Note
此 AppDelegate 类遵循 Flutter 3.41 及更高版本的 iOS 模板,采用了 FlutterImplicitEngineDelegate。如果你的 AppDelegate 类未采用该协议,请省略该协议及 didInitializeImplicitFlutterEngine 方法。改为在 application(_:didFinishLaunchingWithOptions:) 中,于 return super.application(...) 之前,使用根视图控制器的 messenger 创建 channel。保留你的模板中的 GeneratedPluginRegistrant 调用:
GeneratedPluginRegistrant.register(with: self)
let controller = window?.rootViewController as! FlutterViewController
let weightChannel = FlutterMethodChannel(
name: "custom_elements/weight_plan",
binaryMessenger: controller.binaryMessenger
)
class App : Application() {
// the weight plan that your Dart code sends
val weightPlanStore = WeightPlanStore()
override fun onCreate() {
super.onCreate()
AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore))
}
}
class MainActivity : FlutterFragmentActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val weightPlanStore = (application as App).weightPlanStore
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "custom_elements/weight_plan")
.setMethodCallHandler { call, result ->
val currentWeight = call.argument<Double>("current")
val goalWeight = call.argument<Double>("goal")
if (call.method == "setWeights" && currentWeight != null && goalWeight != null) {
weightPlanStore.plan = WeightPlan(currentWeight, goalWeight)
result.success(null)
} else {
result.notImplemented()
}
}
}
}
在 android/app/src/main/AndroidManifest.xml 中命名 App 类,详见将解析器传递给 SDK。
在你的 Dart 代码中,在付费墙流程打开之前,将权重发送给 store:
// your iOS and Android code listens to this channel
const weightPlanChannel = MethodChannel('custom_elements/weight_plan');
Future<void> showWeightPaywall(double currentWeight, double goalWeight) async {
try {
// the native resolver builds the chart from these weights
await weightPlanChannel.invokeMethod('setWeights', {
'current': currentWeight,
'goal': goalWeight,
});
final flow = await Adapty().getFlow(placementId: 'weight_paywall');
final view = await AdaptyUI().createFlowView(flow: flow);
await view.present();
} on AdaptyError catch (adaptyError) {
// handle the error
} catch (e) {
// handle the error
}
}
7. 在设备上测试
Flow & Paywall Builder 无法运行你的应用代码,因此其画布仅显示备用内容。要预览数据图表:
- 发布两个流程。若要查看最新发布的版本而非缓存版本,请将设备注册为测试设备。
- 运行包含解析器的应用构建。在 iOS 上,请使用 iOS 17 或更高版本的设备。完成包含当前体重和目标体重的用户引导流程,验证数据图表的折线是否从当前体重开始,并在目标体重处结束。
- 在数据图表上拖动手指,验证手指所在周的预测体重是否显示在折线上方。
要测试备用方案,请为 line_chart 类型返回空视图,然后重新打开付费墙流程。
要了解为何显示备用方案而非数据图表,请参阅 Flutter 指南中在设备上测试部分的说明。