SDKs
Flutter
Dart package for iOS, Android and web, with a provider, builder widgets and offline storage.
liftcanary is a Dart package for Flutter apps on iOS, Android, the web, macOS, Windows and Linux. Flags are decided on the device from a datafile that is cached and refreshed in the background, so decisions are instant, work offline and give a user the same variation as on your website, in your other apps and on your server.
Install#
flutter pub add liftcanaryOr add it to pubspec.yaml yourself:
dependencies:
liftcanary: ^0.1.0Dart 3.3 and Flutter 3.19 or newer. Its only dependencies are http and shared_preferences.
Set up the provider#
import 'package:flutter/material.dart';
import 'package:liftcanary/liftcanary.dart';
Future<void> main() async {
final storage = SharedPreferencesStorage();
final client = LiftCanaryClient(sdkKey: 'pk_live_...', storage: storage);
final anonymousId = await getAnonymousId(storage); // stable across restarts
runApp(LiftCanaryProvider(
client: client,
user: LiftCanaryUser(anonymousId, attributes: {'plan': 'free', 'country': 'TR'}),
child: const MyApp(),
));
}Create one client for the app and keep it: it starts downloading the datafile and sending events right away. SharedPreferencesStorage can be created before runApp, because it initializes the Flutter binding itself. Widgets that read flags rebuild when a newer datafile arrives, so a kill switch reaches open screens without a restart, and when the provider's user changes (sign-in, new attributes).
Reading flags in widgets#
class Paywall extends StatelessWidget {
const Paywall({super.key});
@override
Widget build(BuildContext context) {
final showTrial = context.liftcanaryFlag('paywall_trial');
final price = context.liftcanaryVariable('paywall', 'monthly_price', 9.99);
return PlanCard(price: price, trial: showTrial, onBuy: () => context.liftcanaryTrack('purchase', value: price));
}
}// A widget per variation
LiftCanaryBuilder('checkout_redesign', builder: (context, decision) => switch (decision.variationKey) {
'one_page' => const OnePageCheckout(),
_ => const ClassicCheckout(),
});
// On / off
LiftCanaryFlag('new_onboarding', fallback: const OldOnboarding(), child: const NewOnboarding());
// A splash screen until the first datafile (at most 3 s; then flags are off)
LiftCanaryReady(placeholder: const Splash(), child: const Home());context.liftcanaryFlag(flagKey)bool | Whether the flag is on. |
context.liftcanaryVariable(flagKey, name, fallback)T | The variable as T, or the fallback when it's missing, null or another JSON kind. int and double convert; use List<Object?> or Map<String, Object?> for JSON. |
context.liftcanaryDecision(flagKey)Decision | flagKey, enabled, variationKey, ruleKey, inExperiment, reason, variables, revision. |
context.liftcanaryTrack(eventKey, value:, properties:)void | Records a goal event. Fine in callbacks: it doesn't subscribe the widget. |
LiftCanaryBuilder(flagKey, builder:)Widget | Builds from the decision: builder(context, decision). |
LiftCanaryFlag(flagKey, child:, fallback:)Widget | Shows child when the flag is on, else fallback (also before the datafile is loaded). |
LiftCanaryReady(child:, placeholder:, timeout:)Widget | Shows placeholder until the first datafile, or until timeout (3 s) passes. |
LiftCanary.of(context)LiftCanaryData | client, user, revision, isReady, decide, isEnabled, getVariable, track. Pass listen: false in callbacks. |
Reading a flag during build logs nothing right away: an experiment exposure is logged once, after the frame that built it, so a build that's thrown away never counts. Exposures are logged once per user, flag, rule and variation.
Without widgets, use the client directly. In pure Dart (a server or a CLI), import package:liftcanary/liftcanary_core.dart, which has no Flutter imports.
await client.ready(timeout: const Duration(seconds: 2));
final user = client.createUser('u-1', attributes: {'plan': 'pro'});
if (user.isEnabled('new_checkout')) showNewCheckout();
final text = user.getVariable('new_checkout', 'button_text', 'Buy now');
user.track('purchase', value: 49.90, properties: {'currency': 'TRY'});Anonymous users and signing in#
getAnonymousId(storage) returns a random id kept under liftcanary:anonymous_id. Pass the same storage as the client: without storage the id lasts only until the app is closed, so the next launch gets a new id and possibly a new variation. Use it as the user id until the person signs in, then give the provider a user with your id and the anonymous id:
final user = LiftCanaryUser(account.id, anonymousId: anonymousId, attributes: {'plan': account.plan}); // LiftCanaryProvider(user: user, ...)With anonymousId, the client sends one identify event per pair, so results count the visits before and after sign-in as one person. Switching ids can change the variation; to keep the one they had while signed out, also pass bucketingId: anonymousId. See From landing page to app.
Offline and the app lifecycle#
- The datafile is polled every 60 seconds (with an ETag, so an unchanged one costs a 304) and downloaded again when the app is resumed.
- With
storage, every downloaded datafile is saved. The next launch still tries the network first, so a kill switch always wins; the saved datafile is used only when the download fails orready()times out. An app opened offline decides with its last configuration. - Events are sent in batches of 20 every 5 seconds. When the app goes to the background, unsent events are stored and sent; the newest 200 survive the app being killed and are sent on the next launch.
- Failed batches are retried with backoff from 1 s to 60 s; a 4xx answer other than 429 drops the batch. Network and data errors are logged, never thrown into the app.
LiftCanaryProviderhandles resume and background. Without a provider, callLiftCanaryLifecycleObserver.attach(client), orclient.onAppForeground()andclient.onAppBackground()yourself.client.close()stops polling, sends the remaining events and stores what couldn't be sent.
On the very first launch there is nothing saved, so without network flags are off until a datafile arrives. To decide immediately even then, ship a datafile as an asset (listed under flutter: assets: in pubspec.yaml) and pass it as datafile:
import 'dart:convert';
import 'package:flutter/services.dart';
// in main(), before creating the client:
WidgetsFlutterBinding.ensureInitialized();
final bundled = jsonDecode(await rootBundle.loadString('assets/liftcanary-datafile.json')) as Map<String, Object?>;
final client = LiftCanaryClient(sdkKey: 'pk_live_...', storage: storage, datafile: bundled);Options#
sdkKeyrequiredString | The environment's public SDK key (pk_…). |
datafileMap<String, Object?> | A datafile to start from (a bundled asset, or from your server): the first decisions need no download. |
storagenone | SharedPreferencesStorage() in apps, InMemoryStorage() in tests, or your own LiftCanaryStorage. Keeps the last datafile, unsent events and the anonymous id. |
cacheDatafiletrue | Use the stored datafile when the download fails or ready() times out. |
pollingInterval60 s | ETag polling. Duration.zero turns it off. |
refreshOnForegroundtrue | Download the datafile when the app is resumed. |
eventBatchSize20 | Events per request. |
eventFlushInterval5 s | How often queued events are sent. |
eventMaxQueueSize1000 | Events held before the oldest are dropped (counted in client.droppedEvents). |
cdnUrlhttps://cdn.liftcanary.com | Where datafiles are served. Your own domain or a self-hosted LiftCanary. |
eventsUrlhttps://events.liftcanary.com | The collector events are sent to. |
httpClienthttp.Client() | Any package:http client (a proxy, tests with MockClient). |
httpTimeout10 s | Timeout of each request. |
loggerLiftCanaryLogger.developer | dart:developer logs (DevTools, nothing in release). LiftCanaryLogger.silent, or your own. |
autoStarttrue | Otherwise call client.start(). |