Encore Flutter SDK
Flutter plugin wrapping the native Encore iOS and Android SDKs. All offer UI is rendered natively — this plugin bridges configuration, identity, placement presentation, purchases, and outcome reporting via platform channels.
Installation
Add to your pubspec.yaml:
dependencies:
encore_flutter: ^2.0.0
iOS
The EncoreKit CocoaPod is automatically included as a transitive dependency of the Flutter plugin — no manual pod configuration is needed.
Minimum deployment target: iOS 15.0.
Android
The com.encorekit:encore AAR is included as a transitive dependency of the Flutter plugin — no manual Gradle configuration is needed.
Minimum SDK: 26.
Usage
Configure
Call once early in your app lifecycle (e.g. in main()):
import 'package:encore_flutter/encore_flutter.dart';
await Encore.shared.configure(
apiKey: 'your_api_key',
purchaseController: AppPurchases(), // see below
logLevel: EncoreLogLevel.debug,
);
transactionLinking defaults to true. Pass false to stop the SDK from
reading the store's purchases (StoreKit history on iOS, Play's active
purchases on Android) and from sending their transaction ids or purchase
tokens to Encore. Encore-attributed claims and purchases still report, but
lift against a control group cannot be measured for your app.
app_account_id still accompanies analytics events.
Run purchases
Encore controls when a purchase happens; your app owns how. Implement
EncorePurchaseController and register the instance at configure — this is
the only purchase path, and the SDK never runs purchase code you did not write.
With no controller registered nothing is ever charged, and a presentation whose
layout offers a product resolves EncorePublisherOutcome.notAttempted.
class AppPurchases implements EncorePurchaseController {
@override
Future<EncorePurchaseResult> purchase(EncorePurchaseRequest request) async {
// request.productId / .placementId / .promoOfferId (iOS) / .basePlanId (Android)
try {
await mySubscriptionManager.purchase(request.productId);
return EncorePurchaseResult.purchased;
} on UserCancelled {
return EncorePurchaseResult.cancelled;
} on PurchaseDeferred {
return EncorePurchaseResult.pending; // Ask to Buy / SCA
}
// Throw for a real failure — Encore records it and resolves the
// presentation with EncorePublisherOutcome.failed.
}
}
The result is three-valued on purpose. pending is a deferred purchase (Ask to
Buy, SCA, a pending Play transaction): the user has not abandoned the flow and
has not been charged yet, so neither purchased nor cancelled is true, and
the store's eventual webhook is the source of truth.
Registration can only happen at configure, because both native SDKs bind the
controller once and expose no setter. It survives reset() — it is app-level
infrastructure, not user state.
Identify User
After authentication:
await Encore.shared.identify(
userId: 'user_123',
attributes: EncoreUserAttributes(
email: 'user@example.com',
subscriptionTier: 'premium',
),
);
Update Attributes
await Encore.shared.setUserAttributes(
EncoreUserAttributes(billingCycle: 'annual'),
);
Language
You don't need to do anything for Encore's copy to follow the user's language. The SDK sends the device language with every request, and Encore serves the copy in that language when your app has it enabled. Anything else falls back to your app's default language.
If your app has its own language picker, pass the choice to setLanguage(). It
outranks the device language. It is a device preference, not user data, so it
stays across launches and through reset() (logout) until you clear it:
await Encore.shared.setLanguage('pt-BR');
// From a Flutter Locale, use toLanguageTag(): toString() gives 'pt_BR'.
await Encore.shared.setLanguage(locale.toLanguageTag());
setLanguage() takes a BCP 47 tag (fr, pt-BR, zh-Hant-TW); for anything
that is not one, the returned future fails with an ArgumentError. Only the language part is used
(pt-BR picks Portuguese), and only when your app has that language enabled;
otherwise the device language applies, then your app's default.
When the user goes back to "System default", call clearLanguage():
await Encore.shared.clearLanguage();
clearLanguage() keeps the user and every attribute, and refetches the copy
for the device language. It does nothing if no language was set. Text you pass
to .headline() or .subheadline() is shown exactly as you give it, so
translate it yourself.
The language field on EncoreUserAttributes is deprecated. It still works
(the SDK applies it as setLanguage() would) and is removed in the next major
version. Replace EncoreUserAttributes(language: tag) with
Encore.shared.setLanguage(tag).
Present Offers
final result = await Encore.placement('cancel_flow').show();
switch (result) {
case EncoreNotPresented(:final reason):
print('Nothing shown: ${reason.name}');
case EncorePresented(:final outcome):
print('advertiser=${outcome.advertiser} '
'publisher=${outcome.publisher.name} '
'dismissal=${outcome.dismissal.name}');
}
show() never throws. Either nothing appeared — EncoreNotPresented, with a
reason — or the interaction ran and EncorePresented carries the complete
factual record.
That record has two independent funnels plus how the sheet ended:
| Axis | Type | What it records |
|---|---|---|
advertiser |
EncoreAdvertiserOutcome |
How far the Encore offer claim got: notAttempted / claimed / verified / cooldown / failed |
publisher |
EncorePublisherOutcome |
What your purchase controller reported: notAttempted / purchased / cancelled / pending / failed |
dismissal |
EncoreDismissReason |
How the sheet went away |
The two funnels are independent — a single presentation can claim an offer and
run a purchase. notAttempted is a real value ("funnel open, nothing entered
it"), which is a different fact from null ("never presented at all").
There is deliberately no SDK-computed "unlocked" verdict: what a claim means is a property of the variant flow that served it, so any projection over app-global config could contradict the flow that actually ran. Branch on the raw axes:
final converted = result.claim != null ||
result.publisher == EncorePublisherOutcome.purchased;
result.claim reads through both claimed and verified and gives you the
EncoreClaimedOffer — campaignId, advertiserName, and a nullable
transactionId that joins this claim to the completion that lands days later
(the same id the offer-completed webhook and the server-side
sdk_offer_completed event carry). It is nullable because the transaction write
can fail while the claim still happened; the claim is reported either way. It
also has a nullable claimUrl, the attributable link the user opened. The link
carries their transaction id, so treat it as user-specific and keep it out of
third-party logs and analytics.
To give a reward-for-trying prize, check
result.claim?.userConfirmedCompletion == true (see below).
Sheet fonts
Colours and images for the reward sheet come from your Encore portal, or from app code (see Component styles below). Fonts come from your app code only: pass them on the placement.
await Encore.placement('streak_complete')
.appearance(const AppearanceConfig(
sheet: SheetAppearance(
// Text the portal skin marks as heading (typically the title,
// subtitle and primary button).
headingFontFamily: 'Playfair Display',
bodyFontFamily: 'Inter', // all other text
),
))
.show();
The native SDK draws the sheet, so it cannot use a font that is only a
Flutter asset in pubspec.yaml. Also register the font in each native app:
- iOS: add the font files to the Runner target and list them under
UIAppFontsinios/Runner/Info.plist. Pass a nameUIFont(name:size:)loads, such as the PostScript name. - Android: add one
.ttfor.otfper family toandroid/app/src/main/res/font/. The name is looked up as given, then lowercased with every character outside[a-z0-9_]as_, so'Playfair Display'findsres/font/playfair_display.ttf. The lookup is by name at runtime, so keep the fonts in release builds, where resource shrinking would remove them: addandroid/app/src/main/res/raw/keep.xmlwith<resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@font/*" />.
A name the platform cannot load draws the system font (Android logs a
warning). Null or blank, the sheet keeps its own font. Only a placement's
appearance reaches the sheet: a trigger's appearance styles the trigger and
ignores sheet. See docs.encorekit.com.
Component styles
SheetAppearance.components styles named parts of the sheet from app code:
colours, corners, borders, images, a Lottie file and motion per component.
await Encore.placement('streak_complete')
.appearance(AppearanceConfig(
sheet: SheetAppearance(components: {
SheetComponent.primaryButton: const SheetComponentStyle(
fill: SheetColor('#F5C52B'),
cornerRadius: 12,
),
}),
))
.show();
Per property, the Encore portal's Style editor wins, then app code, then the
variant. The native SDK drops a value out of range or that the component cannot
take with one warning. The map cannot be const, because SheetComponent
compares by name.
Observe outcomes
Encore.shared.outcomes.listen((outcome) {
switch (outcome) {
case EncorePlacementPresentation(:final placementId, :final result):
// Send the fields you need, not the whole result: result.claim can
// carry the user's claim link.
analytics.log('encore_presentation', placementId, result is EncorePresented);
case EncoreStrictUnlockVerified(:final transactionId):
entitlements.refresh(transactionId);
}
});
A broadcast Stream carrying every show() resolution — including the ones
that presented nothing — plus strict-unlock verifications.
This is the observation channel; control flow belongs at the call site. Its
reason for existing is EncoreStrictUnlockVerified, which resolves after the
flow that produced it ended, possibly on a later launch, and so can never be a
show() return value. It only fires under EncoreUnlockMode.strict. There is
no replay — subscribe at startup if you want every outcome.
Say why you show it now: the moment
The typical integration is one call: the moment. Location and trigger are optional, and Encore widgets report their own trigger.
await Encore.placement('streak_reward')
.moment(const EncoreMoment.streak(7))
.show();
Moments: streak(days), milestone(value), lapse(days:),
paywallAbandon(count), purchase(amount:, currency:), action(label, count:) and custom(label, value:). The native SDK fills a purchase's
currency when you pass none (the device locale's currency); pass currency
only when the amount is in another one. It also
normalizes a label (photoSaved becomes photo_saved).
Encore widgets take the same moment: EncoreGiftsButton(placement: 'streak', moment: const EncoreMoment.streak(7)), and likewise EncoreTrigger,
EncoreClaimReminder and EncoreClaim. A change updates the mounted widget.
After the moment, pass where the placement sits and the launcher that opened it, both optional:
await Encore.placement('level_complete_popup')
.moment(const EncoreMoment.milestone(12))
.location(EncorePlacementLocation.results)
.trigger(EncoreTriggerStyle.embedded)
.show();
Use EncoreTriggerStyle.embedded when your launcher sits inside a screen,
popup or sheet that shows other content, and EncoreTriggerStyle.standalone
when the launcher is the whole UI that appears (a toast, a drop-down notice, a
floating badge).
Use cases and copy
To present the reward surface instead of the monetization sheet — a brand-funded reward at a moment the user has just accomplished something — set the use case and supply your own copy:
final result = await Encore.placement('streak_complete')
.useCase(EncoreUseCase.rewardUsers)
.headline('7 day streak!')
.subheadline("Here's a little thank you from us")
.show();
useCase defaults to EncoreUseCase.reduceChurn, so existing calls are
unchanged. EncoreUseCase.rewardUsers is claim-only and never presents an
in-app purchase.
Copy resolves in strict priority: the value you pass here, then the value configured in the Encore portal, then the shipped template default. A blank string is ignored, so the chain falls through rather than rendering an empty line.
headline / subheadline apply to both use cases — the native side writes
them into the variable the active template reads.
If a use case resolves no layout of its own, the result is
EncoreNotPresented(reason: EncoreNotPresentedReason.useCaseUnavailable) —
typically because the use case is not enabled for this app. It is a correct
no-op, not an error, and it never falls back to the monetization sheet:
putting an IAP screen in front of a user at a moment they were meant to be
rewarded is worse than showing nothing.
Reward for trying
Describe your own prize on the placement. On a reward-for-trying variant the
sheet promises it up front and, when the user comes back from the advertiser,
asks whether they finished. If they tap "Yes, I completed it" and Encore's
server grants the prize, the claim on the result has
userConfirmedCompletion == true, and that is when you grant it.
identify() is required: the server keeps the count per identified user,
across devices. A user you have not identified, including one after reset(),
still gets the question but never the promise or the flag.
// Once, when the user signs in.
await Encore.shared.identify(userId: user.id);
final result = await Encore.placement('level_complete')
.useCase(EncoreUseCase.rewardUsers)
.publisherReward(const EncorePublisherReward(
id: 'coins_100', // only this leaves the device
title: '100 coins',
detail: 'Added to your wallet', // optional
iconUrl: 'https://example.com/coin.png', // optional, http/https
))
.show();
// Encore's own reward: the claim went through.
final claimed = result.advertiser is EncoreAdvertiserClaimed ||
result.advertiser is EncoreAdvertiserVerified;
// Your prize: the user said they finished and the server granted it.
final claim = result.claim;
if (claim != null && claim.userConfirmedCompletion) {
// transactionId can be null, so dedupe on your user id and the campaign.
wallet.add(100, dedupeKey: '${user.id}:${claim.campaignId}');
}
userConfirmedCompletion is the user's own word, not a verified conversion. It
does not change the advertiser stage (a claimed offer stays claimed) and it
never reaches Encore's payout. Passing a prize commits your app to paying it
when the flag is true. Every other variant ignores the prize, so it is safe to
pass on any reward placement.
The same claim, flag included, also arrives on Encore.shared.outcomes.
Grant the prize from the show() result only, and use the stream for
analytics. Granting from both pays twice.
If your app's reward settings in the Encore portal pay on verification, a
"Yes" never sets the flag. Credit the reward from the offer_completed webhook
instead, once per transactionId, and not from the flag. In the default mode,
grant from the flag and not from the webhook.
The server decides the prize. Every "Yes" is sent to Encore, and the first
"Yes" per user per offer earns it, within a daily limit (default 3 prizes per
user in any 24 hours, clamped to 1 to 10). After a "Yes" the offer stays in
the list until the brand confirms the completion, but the sheet shows no
promise on it and a second "Yes" never earns again. Once the daily limit is
reached the sheet asks without a
prize and the flag is false. To change the daily limit:
await Encore.shared.setPublisherRewardPolicy(
const EncorePublisherRewardPolicy(dailyLimit: 5),
);
Claim button
await Encore.shared.setClaimEnabled(false); // gray out and disable
Turning Encore off
For an app whose user turns off an in-app deals setting:
await Encore.shared.setEnabled(dealsSettingOn); // before configure at launch
Default true; set it any time, before or after configure(). While off,
the native SDK sends nothing: no analytics or lifecycle events (app open,
foreground, background), no error reports, no background network. show()
returns EncoreNotPresented with EncoreNotPresentedReason.disabled and no
UI, and triggers show nothing. A sheet already open finishes normally.
Nothing dropped while off is sent later; turning it back on resumes the SDK's
own work. It is not persisted: every launch starts enabled, so set it from
your app's own setting at launch, before configure(). A launch configured
while off never sends its start-up events (sdk_initialized), even once it
is turned on.
Triggers
Small native views that Encore fills from a server variant and that open an Encore sheet, embedded as platform views so they look and behave the same as in a native app. Each one takes no space until it has something to show, and collapses again when it stops (dismissed, its window ends, holdout, or an id this SDK version does not ship). On other platforms it renders nothing. Give it a bounded width, for example as an item in a scrolling list:
ListView(
children: [
const EncoreTrigger(
id: 'claimReminder',
placement: 'home_feed',
// Optional. Your colours win over the portal's and the look's.
appearance: AppearanceConfig(accentColor: '#DEB769'),
),
...feedItems,
],
)
Every trigger takes:
useCase: the use case of the sheet it opens. Both triggers default toEncoreUseCase.rewardUsers.reduceChurnis not supported yet: the trigger renders nothing for it.icon: the icon the look draws,EncoreTriggerIcon.gift(default),appIcon(your app's store icon from the Encore portal) ornone.alignment: where the look sits when the served look is narrower than the trigger,EncoreAlignment.center(default),leadingortrailing. The trigger itself still fills the width it is given.appearance: brand colours and look for this trigger only; see below.headline,subheadlineandcta: your text for the look, in place of its own. Null or blank, the look shows the text set for it on Encore's side, per look, and a look with no spot for a slot keeps its own text. Plain text on one line, cut to 120 UTF-16 units (an emoji can count as two); line breaks and control characters are removed, and text holding${shows the look's own.ctashows only on a look that draws a button.sheetHeadlineandsheetSubheadline: your headline and subheadline for the sheet the trigger opens (a tap or the automatic open), in place of the sheet's own. Separate fromheadlineandsubheadline, which style the look only. Same text rules; null or blank, the sheet's own text.values: your own words and numbers for the look to draw, by key, for example{'minutes': '60'}for a look that says "60 min".publisherRewardandonResult, as described under Gifts button.
Changing id, placement, useCase, autoOpen or icon starts
the trigger over. Changing alignment, appearance, headline, subheadline, cta,
sheetHeadline, sheetSubheadline, values or publisherReward updates the one on screen; a new map with the same values
changes nothing.
values are checked by the native SDK: at most 16 keys; each key starts
with a lowercase letter followed by letters and digits only, up to 32
characters (minutes, coinsLeft; coins_left is dropped); each value is
1 to 64 characters of plain text with no ${ and no control characters
(newlines included). Anything else is dropped and the look shows its own
default. They never leave the device.
AppearanceConfig styles the trigger only; the sheet it opens keeps its own
look. Every field is optional. A colour you set wins; unset, the accent
comes from your Encore portal's accent, and every colour then from the
served look, then the trigger's default:
| Field | What it colours |
|---|---|
accentColor |
Calls to action, progress and other accents |
backgroundColor |
The background. Set alone, text gets a contrasting colour |
backgroundEndColor |
The second stop of a background gradient, for looks that draw one |
textColor |
Primary text. Applies on its own |
secondaryTextColor |
Secondary copy |
trackColor |
Progress tracks |
onAccentColor |
Ink on the accent (arrows, button labels) |
colorScheme |
EncoreColorScheme.system, light or dark; unset follows your portal setting |
Colours are hex: #RGB, #RRGGBB or #RRGGBBAA. A value the native SDK
cannot read is ignored.
The look fields each change one value of the served look; its layout and size stay:
| Field | What it changes |
|---|---|
fontFamily |
Every text run, at the look's own size and weight |
countdownFontFamily |
The countdown's digits. Unset, fontFamily |
cornerRadius |
The outer corner radius, in points (dp on Android) |
shadow |
EncoreShadow.flat (no shadow), soft or strong |
borderWidth |
A stroke inside the outer shape, in points (dp on Android). Alone, it draws in the look's border colour, else the accent |
borderColor |
The stroke's hex colour. Alone, it draws at the look's border width, else 1 |
backgroundImage |
An image filling the outer shape above backgroundColor, cropped to fill |
backgroundImageCapInsets |
An EdgeInsets in points of the image's own size: set, backgroundImage stretches to the frame with its corners kept (a nine-slice). left is the image's left edge in every text direction. A negative or non-finite side drops the insets, as native does |
iconImage |
An image in the icon slot, in place of the gift or app icon. icon: TriggerIcon.none still draws no icon |
EncoreGiftsButton(
placement: 'streak_complete',
appearance: const AppearanceConfig(
fontFamily: 'Playfair Display',
cornerRadius: 0,
shadow: EncoreShadow.strong,
backgroundImage: 'card_gold',
backgroundImageCapInsets: EdgeInsets.fromLTRB(16, 12, 16, 12),
iconImage: 'trophy',
),
)
Fonts and images are names the native app ships, not Flutter assets. Fonts
use the sheet font lookup (UIAppFonts on iOS, res/font on
Android). Images are, on iOS, an image in the main bundle (an asset catalog
name, as UIImage(named:) loads it) and, on Android, a drawable resource
found as fonts are ('card_gold' finds res/drawable/card_gold.png). Keep
looked-up drawables in release builds as for fonts, for example
tools:keep="@font/*,@drawable/card_gold". A name the platform cannot find
draws the system font (for countdownFontFamily, the fontFamily), or keeps
the look's own background or icon (Android logs one warning per name). On
Android a drawable-night image follows a live light or dark switch, and a
forced colorScheme of light or dark picks the matching image; with
system or unset, the image follows the device. On iOS an asset catalog image
follows the trait. A blank name and
a negative or non-finite length are not sent. These fields style the trigger
only; Encore.placement(...).appearance(...) ignores them, as the native
sheet does. Requires the 2.6.0 native SDKs.
What a trigger does after a claim, and after the claimed offer completes, is decided by Encore, not set in code.
Heights come from the look Encore serves (its server template), so a look and its height can change without an SDK update. Don't reserve a fixed height: the trigger sizes itself.
Gifts button
A button or card ("You have a gift"). Tapping it opens the normal Encore
sheet for the use case and placement, as
Encore.placement(...).useCase(...).show() would. It shows only when
there are offers for that use case and placement. After a claim, or once a
claimed offer completes, Encore may turn it into the claim reminder (with
its ×), a thank-you look, or nothing, as the served look says.
EncoreGiftsButton is the same as
EncoreTrigger(id: 'giftsButton', ...):
const EncoreGiftsButton(placement: 'streak_done')
Whether the button may open its sheet by itself (at most once per placement
per day, then it keeps showing the same look) is decided by Encore per served
look. Pass
autoOpen: EncoreAutoOpen.off to opt out: only a tap opens it then, whatever
the look says.
To offer your own prize on the sheet the button opens, pass
publisherReward, as you would with Encore.placement(id).publisherReward(...).
onResult gets the same result show() returns, once for every sheet the
button opens, including one it opens by itself:
EncoreGiftsButton(
placement: 'streak_done',
publisherReward: const EncorePublisherReward(
id: 'coins_500',
title: '500 coins',
),
onResult: (result) {
if (result.claim?.userConfirmedCompletion == true) grantCoins(500);
},
)
When the gift waits on something in your app, pass hostState. While it is
EncoreGiftsButtonHostState.locked(...), a tap opens nothing and the look
shows a hint; ready and done tap as usual. Progress is clamped to 0 to 1,
and lockedSteps(completed:, total:) gives it as steps. A change redraws the
button in place, with no new request. The status and the progress go to the
native SDK, which sends only the status to Encore.
onShowingChange tells you whether a look is drawn, on the first answer and
then on each change, so you can draw your own view until it says false:
EncoreGiftsButton(
placement: 'morning',
hostState: lessonsDone < 4
? EncoreGiftsButtonHostState.lockedSteps(completed: lessonsDone, total: 4)
: EncoreGiftsButtonHostState.ready,
onShowingChange: (showing) => setState(() => giftShowing = showing),
)
Claim reminder
A banner that reminds a user about an offer they claimed but have not
finished. Tapping it opens the Encore sheet with that offer in it. Once the
claimed offer completes, Encore may show its thank-you look instead, as the
served look says. EncoreClaimReminder is the same as
EncoreTrigger(id: 'claimReminder', ...):
const EncoreClaimReminder(placement: 'home_feed')
Encore picks the look on its side, running an experiment between looks when one is set up.
Build your own button
The triggers above are the quickest way in. When your app needs its own
design, keep your own button or card and let Encore drive it with
EncoreClaim. Encore decides what to show; you draw it. It hands your
builder one of four states and a controller:
| State | Draw |
|---|---|
EncoreClaimHiddenState |
Nothing: no offers, holdout, not configured yet, a failure, the churn use case, or a completed claim when Encore hides it after one |
EncoreClaimGiftsState(offerCount, logoUrls) |
Your gifts entry |
EncoreClaimReminderState(advertiserName, logoUrl, perk, claimedAt, deadline, claimCount, transactionId) |
A reminder for an offer the user claimed and has not finished |
EncoreClaimThanksState(offerCount, logoUrls) |
A thank-you after a completed claim, when Encore shows one |
What it turns into after a claim (the reminder, or the gifts again), after a completed claim (the gifts, a thank-you or nothing), and whether the sheet may open by itself are set per served look on Encore's side, so they can be tested like any look. If those rules cannot be fetched, it behaves as it always has: the reminder while a claim is open, then the gifts again. A failure never hides your button while the sheet has offers.
EncoreClaim(
placement: 'streak_done',
onResult: (result) {
if (result.claim?.userConfirmedCompletion == true) grantCoins(500);
},
builder: (context, state, claim) => switch (state) {
EncoreClaimHiddenState() => const SizedBox.shrink(),
EncoreClaimGiftsState(:final offerCount) => ListTile(
title: Text('$offerCount gifts waiting'),
onTap: () => claim.tap(),
),
EncoreClaimReminderState(:final advertiserName) => ListTile(
title: Text('Finish your $advertiserName offer'),
onTap: () => claim.tap(target: EncoreClaimTarget.card),
trailing: IconButton(
icon: const Icon(Icons.close),
onPressed: claim.dismiss,
),
),
EncoreClaimThanksState() => ListTile(
title: const Text('Nice work, you finished it'),
onTap: () => claim.tap(),
),
},
)
Only need to show or hide one entry? EncoreClaim.child draws your widget only
while there are offers (gifts, a reminder or a thanks), and nothing otherwise, so
it takes no space. A tap anywhere on it opens the sheet. Use a child that takes no
taps of its own: a button or InkWell inside wins the tap.
EncoreClaim.child(
placement: 'streak_done',
semanticsLabel: 'Open your gifts',
child: const GiftsRow(),
)
To draw your own widget either way, read state.hasOffers in the builder. It
is true for every state but EncoreClaimHiddenState, as hasOffers on the
native claim handle, and the builder runs again whenever it changes.
EncoreClaim(
placement: 'streak_done',
builder: (context, state, claim) => MyGiftsButton(
enabled: state.hasOffers,
onTap: () => claim.tap(),
),
)
claim.tap()opens the reward sheet and returns the same resultshow()does.target(button,card,arrow) is what analytics counts. One tap at a time: a second one while a sheet is up completes at once as not presented,alreadyPresenting. A tap still open when the widget goes away completes with the sheet's result, andonResultstill gets it.claim.dismiss()hides a reminder on this device.autoOpen: EncoreAutoOpen.offkeeps the sheet from opening by itself. Left out, Encore decides per served look (at most once a day, and only after your view was seen);offalways wins.sheetHeadlineandsheetSubheadlineset the text of every sheet it opens, as onEncoreTrigger. Changing them,publisherRewardoronResultupdates the current handle.
Encore counts a view when at least half of what builder draws is on
screen for a second, with no route or dialog over it, not on a hidden
IndexedStack page, and with the app in the foreground. Changing placement,
useCase or autoOpen starts a new handle, hidden until it loads. A sheet
Encore opened by itself that is still up when the widget goes away, or when
one of those changes, may not report its result; a sheet opened by
claim.tap() always does.
Reset (Logout)
await Encore.shared.reset();
Migrating from 1.x
2.0 tracks the native Encore 2.0 SDKs, which removed onPurchaseRequest
entirely and replaced it with a registered purchase controller. There is no
compatibility shim, because the only shim available would have had to collapse
the three-valued purchase result back into 1.x's void/bool — which is
exactly the bug 2.0 fixes.
| 1.x | 2.0 |
|---|---|
Encore.shared.onPurchaseRequest(handler) |
Implement EncorePurchaseController, pass it to configure(purchaseController:) |
Encore.shared.onPurchaseRequestResult(handler) |
Same — and return pending instead of false for deferred purchases |
Encore.shared.onPurchaseComplete(handler) |
Removed. The SDK no longer runs purchases itself, so there is no native purchase to report — your controller already sees every purchase it runs |
Encore.shared.onPassthrough(handler) |
Removed. Read the result instead: EncoreNotPresented means nothing was shown, and a presented record carries the dismissal and both funnels |
Encore.shared.placements.setClaimEnabled(x) |
Encore.shared.setClaimEnabled(x) |
EncorePresentationResultGranted |
EncorePresented + result.claim != null || result.publisher == EncorePublisherOutcome.purchased |
EncorePresentationResultClaimed |
EncorePresented + result.claim != null |
EncorePresentationResultNotGranted(reason: String) |
EncoreNotPresented(reason: EncoreNotPresentedReason) for "nothing shown", or EncorePresented + outcome.dismissal for "shown, then dismissed" — 1.x conflated the two |
EncoreBillingPurchaseResult |
Removed with onPurchaseComplete |
'use_case_unsupported' |
Gone. 1.x dropped the use case at the bridge, so rewardUsers could never present; 2.0 forwards it, leaving EncoreNotPresentedReason.useCaseUnavailable as the only unavailability reason |
Before:
await Encore.shared.configure(apiKey: 'key', logLevel: EncoreLogLevel.debug);
Encore.shared.onPurchaseRequestResult((request) async {
return await mySubscriptionManager.purchase(request.productId);
});
Encore.shared.onPassthrough((placementId) => runOriginalAction());
final result = await Encore.placement('cancel_flow').show();
if (result is EncorePresentationResultGranted) grantAccess();
After:
class AppPurchases implements EncorePurchaseController {
@override
Future<EncorePurchaseResult> purchase(EncorePurchaseRequest request) async {
return await mySubscriptionManager.purchase(request.productId)
? EncorePurchaseResult.purchased
: EncorePurchaseResult.cancelled; // or .pending, when deferred
}
}
await Encore.shared.configure(
apiKey: 'key',
purchaseController: AppPurchases(),
logLevel: EncoreLogLevel.debug,
);
final result = await Encore.placement('cancel_flow').show();
if (result.claim != null ||
result.publisher == EncorePublisherOutcome.purchased) {
grantAccess();
} else {
runOriginalAction(); // what onPassthrough used to do
}
Architecture
Flutter App
│
▼
┌──────────────────────────────────────┐
│ Encore Dart API │
│ (lib/src/encore.dart) │
├──────────────────┬───────────────────┤
│ MethodChannel │ EventChannel │
│ com.encorekit/ │ com.encorekit/ │
│ encore │ encore/outcomes │
├──────────────────┼───────────────────┤
│ iOS Plugin │ Android Plugin │
│ (Swift) │ (Kotlin) │
├──────────────────┼───────────────────┤
│ EncoreKit │ com.encorekit │
│ CocoaPod │ :encore AAR │
└──────────────────┴───────────────────┘
The method channel carries request/response calls in both directions: the purchase controller is a reverse call, where native asks Dart to run the purchase and suspends until Dart answers. Dart cannot implement a Swift protocol or a Kotlin interface, so each plugin owns the native conformance and forwards over the channel.
Android's native controller is additionally handed the foreground Activity;
the plugin absorbs it — it is valid only for the duration of the call and must
not be retained, and iOS has no equivalent — so the Dart contract is identical
on both platforms.
The event channel carries the outcomes stream, which is one-way and unbounded
and so cannot ride a request/response method call. It bridges an AsyncStream
on iOS and a SharedFlow on Android onto one Dart broadcast Stream.
Public API: one way, fluent
Every public action has one entry point, written as a fluent chain that mirrors the Swift SDK: Encore.placement(id).useCase(EncoreUseCase.rewardUsers).show(). Encore.shared.placement(id) is deprecated and removed in 3.0; use Encore.placement(id). Do not add a second entry point, a convenience overload that restates a call, or a deprecation that steers callers. Deprecate only what is being removed. Full rule and review check: Public SDK API: one way, fluent.
API Reference
| Method | Description |
|---|---|
Encore.shared.configure(apiKey:, purchaseController:, logLevel:, unlock:, transactionLinking:) |
Initialize the SDK and register the purchase controller |
Encore.shared.identify(userId:, attributes:) |
Associate user identity |
Encore.shared.setUserAttributes(attributes) |
Merge user attributes |
Encore.shared.setLanguage(tag) |
Show Encore's copy in the app-chosen language (a BCP 47 tag) instead of the device language |
Encore.shared.clearLanguage() |
Remove the language set by setLanguage so copy follows the device language again |
Encore.shared.reset() |
Clear user data (logout); the purchase controller and the language set by setLanguage survive |
Encore.setPersonalization(enabled) |
Your app's own personalization switch for this user, only for apps that have one; saved on the device. Also a configure(personalization:) option |
Encore.shared.setClaimEnabled(enabled) |
Enable/disable the claim CTA |
Encore.shared.setEnabled(enabled) |
Turn the SDK off (or back on) for this launch; on by default, not saved |
Encore.shared.isClaimEnabled() |
Read whether the claim CTA is enabled, from the native SDK; Future<bool>, never throws (true on failure) |
Encore.shared.setPublisherRewardPolicy(policy) |
Daily cap on the reward-for-trying prize (default 3, clamped to 1 to 10) |
Encore.shared.publisherRewardPolicy() |
Read the reward policy the native SDK holds; never throws (the default policy on failure). iOS reports the clamped daily limit, Android the value as set |
Encore.shared.outcomes |
Stream<EncorePlacementOutcome> of every resolved outcome |
Encore.placement(id).show() |
Present the native offer sheet; returns EncorePresentationResult |
Encore.placement(id).moment(moment) |
Say why the app shows the placement now, e.g. EncoreMoment.streak(7); the typical integration passes only this |
Encore.placement(id).location(location) |
Optional: where the placement sits, e.g. EncorePlacementLocation.results |
Encore.placement(id).trigger(style) |
Optional: your own launcher that opened the sheet, EncoreTriggerStyle.embedded or .standalone |
Encore.placement(id).hasOffers() |
Whether show() would find offers for this user now, without opening the sheet; returns Future<bool> and never throws. Select EncoreUseCase.rewardUsers first: reduceChurn always answers false. A false can be cached for up to 5 minutes |
Encore.placement(id).useCase(useCase) |
Select what the placement should achieve: EncoreUseCase.reduceChurn (default) or .rewardUsers |
Encore.placement(id).headline(text) |
Override the sheet headline, on every use case |
Encore.placement(id).subheadline(text) |
Override the sheet subheadline, on every use case |
Encore.placement(id).publisherReward(reward) |
Your own prize for trying an offer; grant it when result.claim?.userConfirmedCompletion == true |
Encore.placement(id).appearance(config) |
Style this presentation's sheet: its colours and the sheet fonts (SheetAppearance(headingFontFamily:, bodyFontFamily:)), registered natively |
EncoreTrigger(id:, placement:, useCase:, autoOpen:, icon:, alignment:, appearance:, headline:, subheadline:, cta:, sheetHeadline:, sheetSubheadline:, moment:, values:, publisherReward:, onResult:, hostState:, onShowingChange:) |
Widget: a native Encore trigger, zero height when there is nothing to show. hostState and onShowingChange apply to the gifts button only |
EncoreGiftsButton(placement:, useCase:, autoOpen:, icon:, alignment:, appearance:, headline:, subheadline:, cta:, sheetHeadline:, sheetSubheadline:, moment:, values:, publisherReward:, onResult:, hostState:, onShowingChange:) |
Widget: EncoreTrigger with the giftsButton id; tap (or autoOpen) opens the sheet with your publisherReward, and onResult gets each sheet's result. hostState locks it until your app says ready; onShowingChange reports whether a look is drawn |
EncoreClaimReminder(placement:, useCase:, icon:, alignment:, appearance:, headline:, subheadline:, cta:, sheetHeadline:, sheetSubheadline:, moment:, values:, publisherReward:, onResult:) |
Widget: EncoreTrigger with the claimReminder id; tap opens the sheet with the claimed offer |
EncoreClaim(placement:, useCase:, autoOpen:, publisherReward:, sheetHeadline:, sheetSubheadline:, moment:, onResult:, builder:) |
Widget: build your own button: your own gifts button or reminder; builder gets an EncoreClaimState and an EncoreClaimController (tap, dismiss) |
EncoreClaim.child(placement:, ..., semanticsLabel:, child:) |
Widget: the one-line form: child only while there are offers, nothing otherwise; a tap opens the sheet. Takes the options EncoreClaim takes |
Libraries
- encore_flutter
- Flutter plugin wrapping the native Encore iOS and Android SDKs.