Flutter setup
Install the Dart SDK, share visitor identity with your web shop, and test flags, goals and purchases in Flutter.
Use the same Apex experiments in a Flutter app and a web shop. Assignments come from Apex; the app never buckets visitors locally. This is a Dart implementation, with Flutter adapters for lifecycle, platform detection and durable storage.
Install
flutter pub add drip_apexOr add it to pubspec.yaml and run flutter pub get:
dependencies:
drip_apex: ^0.1.0Requires Dart 3.5+ and Flutter 3.24+. Supported platforms: Android, iOS and web.
Configure and read flags
import 'package:drip_apex/drip_apex.dart';
import 'package:flutter/widgets.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Apex.configure(const ApexOptions(
publishableKey: 'apx_pk_live_YOUR_KEY',
shopId: 'YOUR_SHOP_ID',
applicationId: 'com.example.shop',
appVersion: '1.0.0',
environment: 'production',
));
final enabled = Apex.flag<bool>('new_checkout', defaultValue: false);
// Use enabled to choose your checkout. Then runApp(yourApp).
}Create the publishable key in Settings → Developers. Ship only the
apx_pk_… key in the app, never a private management API key. Configure waits
for storage and the first assignment response or initTimeout (three seconds
by default). Offline reads use cached values or the defaults you supply.
flag<T> accepts bool, String, int, double, Map and List JSON values.
Missing or incompatible values return the default. Use flagObject<T> for
validated app models:
final title = Apex.flagObject<String>('welcome',
defaultValue: 'Welcome',
decode: (json) => (json as Map)['title'] as String,
);
final variation = Apex.variation('welcome', exposure: ApexExposure.manual);
Apex.logExposure('welcome'); // Call when this content becomes visible.A failed decoder returns the default and records no exposure. Successful reads
record one exposure per identity, experiment, variation and assignment epoch
per session. Use ApexExposure.manual for reads of content not yet visible.
variation.reason is fresh, cached, stale (after 60 seconds), default,
or override. To update your UI, subscribe to changed keys:
final subscription = Apex.onChange((change) {
if (change.type == 'changed') {
// Re-read change.keys and rebuild your widget.
} else {
// change.code explains a stopped SDK, for example a revoked key.
}
});
// In dispose:
subscription.cancel();Consent
Consent defaults to ApexConsent.granted. EU apps should start with
ApexConsent.pending and pass their consent management platform (CMP) decision
to the SDK:
await Apex.configure(const ApexOptions(
publishableKey: 'apx_pk_live_YOUR_KEY',
shopId: 'YOUR_SHOP_ID',
consent: ApexConsent.pending,
));
// In your CMP decision callback:
await Apex.setConsent(true); // Grant consent and fetch assignments.
await Apex.setConsent(false); // Revoke consent and wipe SDK storage.ApexConsent.denied and ApexConsent.pending send no network requests and
write nothing to storage. The device ID stays in memory, flags return your
defaults (variation.reason is default), and events, purchases and exposures
are dropped rather than saved for later. This also applies to QA overrides.
Identify updates only the in-memory identity until consent is granted.
Granting consent persists the current device and user identity and fetches
assignments. Revoking immediately stops new requests, ignores outstanding
responses, clears in-memory events and assignments, and deletes this shop and
environment's queue, cache and identity plus the shared apex_device_id key.
Await revocation to wait for the storage wipe; a deletion failure throws so your
app can retry. Other shop/environment cache, queue and identity keys are kept.
Use await client.setConsent(granted) with an independent ApexClient.
The SDK does not install WebView cookies or clear cookies your app installed.
Share identity with the web shop
Logged-in customers: call await Apex.identify('customer-123') with exactly
the ID your web shop uses. await Apex.identify(null) logs out and returns to
the persisted anonymous device identity. Identity changes immediately drop the
previous assignments and serve the new identity's cached entry (cached or
stale) or defaults (default) until its response arrives, with exposures
suppressed while pending, including after a timeout. The user ID persists per
shop and environment, including across cold launches.
Anonymous visitors: pass the web shop's drip_uid before configuring:
await Apex.configure(ApexOptions(
publishableKey: 'apx_pk_live_YOUR_KEY',
shopId: 'YOUR_SHOP_ID',
visitorId: webDripUid, // 32 lowercase hex characters, or a UUID.
));
final cookie = Apex.webViewCookie(domain: 'example.com');
// Set cookie with your WebView's cookie API before loading the shop.Apex.deviceId is the exact persisted device identity. A supplied visitorId
accepts 32 lowercase hex characters or a UUID and replaces the stored identity
only when explicitly passed. New device IDs use the web drip_uid format:
32 lowercase hex characters generated from 16 secure random bytes. Existing
stored IDs, including legacy UUIDs, are preserved verbatim.
Apex.visitorId returns that same string without changing case or removing
hyphens. webViewCookie returns drip_uid=<id>; Domain=example.com; Path=/; Max-Age=31536000; Secure; SameSite=Lax with the same identity sent to
/v1/assign while anonymous and used for anonymous events. It returns null
until consent is granted and Apex.configure has finished, so a WebView never
receives the ID without consent or before the saved ID is loaded.
Assignment is per identity string. Use the exact same anonymous ID in the app and web shop, including any hyphens in a legacy UUID. Set the helper's cookie before loading the WebView. The helper does not install cookies or configure your WebView for you.
Goals and purchases
await Apex.track('newsletter_signup', {'placement': 'footer'});
await Apex.trackPurchase(
orderId: 'A1', revenue: 99.9, currency: 'EUR',
properties: {'screen': 'checkout'},
);
await Apex.flush();Use a stable order ID and non-negative finite revenue in currency units, with a
three-letter currency code. Purchases create a base event and one copy per
served experiment; custom events are unattributed. Explicit order, revenue and
currency arguments replace any aliases in properties. Properties must be JSON.
Never send email, phone, password, ssn, credit_card or card_number,
including case or accent variants. Invalid events are dropped with a diagnostic
when a logger is supplied. Generic revenue properties accept finite numbers or
plain decimal strings such as "42,5"; exponential strings such as "1e3" are rejected.
QA builds
await Apex.configure(const ApexOptions(
publishableKey: 'apx_pk_live_YOUR_KEY', shopId: 'YOUR_SHOP_ID', qaMode: true,
overrideValues: {'welcome': {'enabled-variation-id': true}},
));
Apex.setOverride('welcome', 'enabled-variation-id');
Apex.handleQaLink(Uri.parse('myapp://qa?apex_force=welcome:enabled-variation-id'));
Apex.clearOverrides();Your app routes its deep links to handleQaLink; the SDK does not register a
scheme. Comma-separated flagKey:variationId pairs are supported. Invalid pairs
are ignored. Overrides require qaMode: true; otherwise they are ignored with a
warning. Overridden reads never record exposures. If the selected variation was
not served by Apex, reads return your default unless overrideValues supplies
that variation's value. variation reports reason: 'override'. Events are
marked qa_mode: true while an override is active, and throughout a QA build.
Non-production environments are QA traffic too. Queued events retain their mark.
To test the real served value of another variation, register Apex.deviceId
(or Apex.userId after identify) as a server-side QA device at
/api/v1/flags/{id}/qa-devices, using your private key from a trusted terminal.
See Test your build.
Results hide QA events unless you enable the QA toggle. Store builds use
qaMode: false and environment: 'production'.
Lifecycle and offline delivery
The Flutter observer flushes on pause/detach and refreshes once on resume with
0–10 seconds of jitter. Thirty continuous minutes in the background create a
new session. There is no assignment polling; use Apex.refresh() for an explicit
refresh. Events use ios, android or web, sdk_version: flutter-0.1.0, and
app://com.example.shop/<screen> URLs. Hosts are lowercased with underscores
replaced by hyphens; screen query/fragment characters are encoded into the path.
Provide screen: () => currentRoute or properties.screen to name a screen.
Events persist before delivery, retain stable IDs on retry, and expire after 47
hours. ApexOptions.maxQueuedEvents sets the queue capacity in rows (default
2,000; valid range 100–50,000 inclusive). Invalid values stop the client without
networking. Oldest groups are evicted whole; a purchase group larger than the
configured capacity is dropped whole. Batches target 20 rows per request, or up
to 100 rows while 100 or more rows are queued. Purchase groups stay together:
small batches can expand, and a group larger than 100 rows is sent alone, up to
the 200-row server limit. Groups exceeding the server limit are dropped whole.
HTTP 202 with ok: true acknowledges rows by
(event_id, experiment_id, variation_id), then immediately continues draining
any remaining backlog, one request at a time.
429 and retryable server responses respect Retry-After (seconds or HTTP date);
lookup-unavailable defaults to five seconds. Other network/server failures back
off from five to sixty seconds with jitter. Unknown 401/403 retry after five
minutes. Non-retryable event 4xx drop that batch, except 401/403/408/429; explicit
retryable 4xx retain it and retry after thirty seconds. Fatal 401 codes
invalid_publishable_key and publishable_key_not_allowed stop both lanes once.
Requests time out after thirty seconds and refuse redirects.
Storage, tests and independent clients
ApexOptions.storage, transport, clock and logger are injectable.
ApexStorage defines read, write and delete; the default is
SharedPreferencesStorage. For tests use MemoryStorage and an ApexTransport
fake. Writes must replace atomically or fail without changing the value.
Identity storage failure stops networking; a later successful identify write
resumes it. Queue write failures retain the prior queue for safe replay.
The device key is apex_device_id. Other keys use
apex_flutter_<base64url(shopId + "\n" + environment)> plus -cache, -events
and -identity. Cache retains four identities. For two shops create separate
ApexClient(options) instances and await each ready; use their instance methods.
Apex.shutdown() (or client.shutdown()) removes lifecycle observers and timers.
Core files under lib/src/core import no Flutter libraries.
flutter pub get
dart format --set-exit-if-changed lib test
flutter analyze
flutter test --concurrency=2
cd example
flutter pub get
flutter analyze
flutter test --concurrency=2Troubleshooting
- Flag stays at its default: check the key, API-delivery flag, environment, audience and publishable key. App SDKs do not receive storefront URL-targeted flags.
- Web and app differ: compare the exact
/v1/assignidentity strings; use identical customer IDs or the exact same anonymous ID on both sides. - No QA value: client overrides need
qaModeand a registered local value; use server QA devices to fetch an actual different served variation. - No uploads: await configure, check durable storage, then flush. Supply
logger: (line) => debugPrint(line)for safe diagnostics; never log keys. - SDK stopped: replace a revoked/invalid key and configure again. A transient key lookup outage retries and does not mean the key is invalid.
See Test your build for server-side QA devices and the device event lookup. See Goals and purchases for attribution and Users and identity for identity rules.