uplift_funnel_flutter 0.5.0
uplift_funnel_flutter: ^0.5.0 copied to clipboard
Uplift Funnel Flutter SDK. Renders onboarding flows as native Flutter widgets — no WebView. Build the flow in the Uplift Funnel dashboard, show it with one widget, and change it later without shipping [...]
example/lib/main.dart
// Minimal demo: one-key configure + one-widget render. Pass your key at build
// time and point kFlowKey at a flow in your dashboard app:
// flutter run --dart-define=UPLIFT_FUNNEL_API_KEY=fnl_pk_…
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
import 'package:uplift_funnel_flutter/uplift_funnel_flutter.dart';
// Supplied at build time so no key is committed:
// flutter run --dart-define=UPLIFT_FUNNEL_API_KEY=fnl_pk_…
// `pnpm seed` in funnel-api prints a fresh local key; a real app uses its own
// public key from the dashboard.
const kApiKey = String.fromEnvironment('UPLIFT_FUNNEL_API_KEY');
// Dev-server override, defaulted to a local API in debug and to nothing in
// release — so a release build of this example talks to production instead of
// tripping the SDK's cleartext check. Android emulator can't see the host's
// `localhost`: use http://10.0.2.2:3000 there. iOS sim / desktop / physical
// devices on the same network: http://localhost:3000 (or your machine's LAN IP).
const kServerUrl = String.fromEnvironment('UPLIFT_FUNNEL_API_URL',
defaultValue: kDebugMode ? 'http://localhost:3000' : '');
// Overridable so one build can be pointed at any flow in the dashboard app:
// flutter run --dart-define=UPLIFT_FUNNEL_FLOW_KEY=glow
const kFlowKey = String.fromEnvironment('UPLIFT_FUNNEL_FLOW_KEY',
defaultValue: 'otro-second-phone-number');
// An A/B experiment key (dashboard → Experiments). `UpliftFunnelFlow.experiment`
// routes through it: the SDK attaches a sticky per-install subject id so the
// server buckets this device into a stable variant, and the chosen variant's
// flow renders. Safe to leave in production — a stopped experiment serves the
// baseline, a rolled-out one the winner.
const kExperimentKey = 'test-onboarding';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await UpliftFunnel.configure(
apiKey: kApiKey,
// Empty means "use the default production host".
serverUrl: kServerUrl.isEmpty ? null : kServerUrl,
);
// ── Native handoffs ────────────────────────────────────────────────────
// The flow JSON declares WHAT happens (a signin gate, a permission ask, a
// paywall CTA, a Terms link); these handlers are HOW your app does it.
// Every one is optional, so you can wire them one at a time. Without a
// handler the SDK degrades honestly rather than faking a result: a
// permission ask shows a stand-in dialog (so the deny branch is reachable),
// and a photo tile stays inert instead of storing a placeholder.
//
// This demo fakes each with a confirm dialog. In a real app you'd call:
// signin → sign_in_with_apple / google_sign_in (+ your backend)
// permission → permission_handler (Permission.notification.request()…)
// purchase → purchases_flutter (RevenueCat) / adapty_flutter
// photo → image_picker (ImagePicker().pickImage)
// link → url_launcher (launchUrl)
UpliftFunnel.registerSignInHandler((provider) async {
// e.g. SignInWithApple.getAppleIDCredential(...) when provider == 'apple'
return _confirm('Sign in with $provider?');
});
UpliftFunnel.registerPermissionHandler((permission) async {
// e.g. (await Permission.notification.request()).isGranted
return _confirm('Grant $permission permission?');
});
UpliftFunnel.registerPurchaseHandler((request) async {
// e.g. Purchases.purchaseStoreProduct(byId(request.productId)) —
// map cancel/failure to PurchaseResult so the user stays on the paywall
// and analytics records the drop-off.
final ok = await _confirm(
'Purchase "${request.productId ?? request.planId ?? '—'}" '
'(plan ${request.planId ?? '—'})?',
);
return ok ? PurchaseResult.purchased : PurchaseResult.cancelled;
});
// Runtime product catalog for paywall display. In a real app, map your
// billing SDK's offerings (e.g. RevenueCat StoreProduct.priceString) —
// plan cards with a matching `product_id` auto-show these instead of the
// prices authored in the dashboard, and any text node can interpolate
// {{price.yearly_pro}} / {{price_per_month.yearly_pro}} / {{trial_days...}}.
UpliftFunnel.setProducts(const [
UpliftFunnelProduct(
id: 'yearly_pro',
price: r'$59.99',
priceAmount: 59.99,
period: ProductPeriod.year,
trialDays: 7,
trialEligible: true,
),
UpliftFunnelProduct(
id: 'monthly_pro',
price: r'$9.99',
priceAmount: 9.99,
period: ProductPeriod.month,
),
]);
UpliftFunnel.registerPhotoUploadHandler((request) async {
// e.g. (await ImagePicker().pickImage(
// source: request.source == 'camera'
// ? ImageSource.camera
// : ImageSource.gallery,
// ))?.path
debugPrint('photo requested: source=${request.source}');
return 'demo://photo';
});
UpliftFunnel.registerLinkHandler((url) {
// e.g. launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication)
debugPrint('open link: $url');
final context = navigatorKey.currentContext;
if (context != null) {
ScaffoldMessenger.maybeOf(context)
?.showSnackBar(SnackBar(content: Text('Would open $url')));
}
});
runApp(const UpliftFunnelExampleApp());
}
/// Stand-in for a real OS dialog / auth sheet / purchase sheet.
Future<bool> _confirm(String message) async {
final context = navigatorKey.currentContext;
if (context == null) return true;
final ok = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text("Don't Allow")),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Allow')),
],
),
);
return ok ?? false;
}
class UpliftFunnelExampleApp extends StatelessWidget {
const UpliftFunnelExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
title: 'Uplift Funnel demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFFFF6B35)),
useMaterial3: true,
),
home: const _HomeMenu(),
);
}
}
/// Two entry points: the plain onboarding flow, and the same flow routed
/// through an A/B experiment. Both push a [_FlowHostScreen] that renders
/// full-screen and forwards completion to [_DoneScreen].
class _HomeMenu extends StatelessWidget {
const _HomeMenu();
void _open(BuildContext context, {required bool experiment}) {
navigatorKey.currentState?.push(
MaterialPageRoute<void>(
builder: (_) => _FlowHostScreen(experiment: experiment),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Uplift Funnel demo')),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Pick a flow to run',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
FilledButton.icon(
onPressed: () => _open(context, experiment: false),
icon: const Icon(Icons.play_arrow),
label: Text("Onboarding flow ($kFlowKey)"),
),
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: () => _open(context, experiment: true),
icon: const Icon(Icons.science_outlined),
label: Text("A/B experiment ($kExperimentKey)"),
),
const SizedBox(height: 24),
const Text(
'The A/B route uses UpliftFunnelFlow.experiment — the device is '
'stickily bucketed into a variant, and onCompleted reports '
'which one ran.',
style: TextStyle(color: Colors.black54, fontSize: 13),
textAlign: TextAlign.center,
),
],
),
),
),
);
}
}
/// Hosts either the default or the experiment variant of [UpliftFunnelFlow] and
/// routes completion to the done screen. Kept in its own screen so each run
/// starts a fresh session.
class _FlowHostScreen extends StatelessWidget {
const _FlowHostScreen({required this.experiment});
final bool experiment;
void _onCompleted(BuildContext context, UpliftFunnelFlowResult result) {
// result.experiment is the typed UpliftFunnelExperimentAssignment (or null for
// the non-experiment flow) — log which variant the user actually saw.
debugPrint('flow complete: $result — variant: ${result.experiment}');
navigatorKey.currentState?.pushReplacement(
MaterialPageRoute<void>(builder: (_) => _DoneScreen(result: result)),
);
}
@override
Widget build(BuildContext context) {
// Same loading / error / retry UX for both — only the constructor differs.
final flow = experiment
? UpliftFunnelFlow.experiment(
kExperimentKey,
onCompleted: (result) => _onCompleted(context, result),
)
: UpliftFunnelFlow(
kFlowKey,
onCompleted: (result) => _onCompleted(context, result),
);
// UpliftFunnelFlow is full-bleed: it paints its own background edge-to-edge and
// runs its own SafeArea for content. Do NOT wrap it in SafeArea/padding —
// that would inset the flow and expose the Scaffold background as strips.
return Scaffold(body: flow);
}
}
/// Global navigator so `onCompleted` (fired from inside [UpliftFunnelFlow], which
/// has no `BuildContext` of its own at that point) can push the done page.
final navigatorKey = GlobalKey<NavigatorState>();
class _DoneScreen extends StatelessWidget {
const _DoneScreen({required this.result});
final UpliftFunnelFlowResult result;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Flow complete')),
body: SafeArea(
child: ListView(
padding: const EdgeInsets.all(20),
children: [
Text(
'Ended: ${result.endReason}',
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w700),
),
const SizedBox(height: 4),
Text('Source: ${result.source.name}',
style: const TextStyle(color: Colors.black54)),
if (result.experiment != null) ...[
const SizedBox(height: 4),
Text(
'Experiment: ${result.experiment!.experimentId} → '
'${result.experiment!.variantName ?? result.experiment!.variantId}',
style: const TextStyle(
color: Color(0xFFFF6B35), fontWeight: FontWeight.w600),
),
],
const SizedBox(height: 20),
const Text(
'COLLECTED VARIABLES',
style: TextStyle(
fontWeight: FontWeight.w700,
letterSpacing: 1.1,
fontSize: 12),
),
const SizedBox(height: 8),
if (result.variables.isEmpty)
const Text('(none)', style: TextStyle(color: Colors.black45))
else
for (final entry in result.variables.entries)
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
Expanded(
child: Text(entry.key,
style: const TextStyle(
fontWeight: FontWeight.w600))),
Expanded(
child:
Text('${entry.value}', textAlign: TextAlign.end)),
],
),
),
],
),
),
);
}
}