تخطَّ إلى المحتوى

Flutter

التثبيت

flutter pub add heysada_nida

شرح الاستخدام أدناه بالإنجليزية، كما يظهر في سجل الحزمة، والشيفرة نفسها في كل لغة.

In-app messages from reach (the repository, task 114): banners, popups, full-screen messages and an inbox, plus push opens, track and consent. Every message is drawn with Flutter widgets. There is no native UI and no WebView, so callbacks behave the same on Android and iOS, and a message runs in its own direction (dir) inside a Directionality. Impressions, clicks and dismissals are reported, queued on the device and retried. Nothing the SDK does throws into the app.

Use it

dependencies:
  heysada_nida: ^0.1.0   # each brand's package, built with its name (config/brands.json, task 102)
final navigatorKey = GlobalKey<NavigatorState>();

AppMessages.configure(AppMessagesOptions(
  appKey: 'ipk_…',                          // the panel → Keys (publishable)
  apiUrl: 'https://inapp.example.com',      // where reach-inapp serves /sdk/v1
  placements: ['home_top', 'home_popup', 'inbox'],  // every placement the app shows, at most 10
  profilesUrl: 'https://profiles.example.com',      // for track and consent
  profilesKey: 'pk_…',                      // the panel → Settings → Profile keys (publishable)
  onOpenUrl: (url, message) => myRouter.open(url),  // the SDK opens no link itself
  onPushOpened: (messageId, placement) => myRouter.openOffers(),
));
await AppMessages.identify(user.id);            // your own opaque id; nothing shows before it
// with identity verification: userHash = hex(HMAC-SHA256(identity secret, user.id)), from your server
// await AppMessages.identify(user.id, userHash: user.sadaHash);
await AppMessages.setConsent('in_app', true);   // strict: without it, nothing is decided

runApp(AppMessagesScope(navigatorKey: navigatorKey, child: MyApp(navigatorKey: navigatorKey)));

// where the app wants them:
const MessageBanner(placement: 'home_top');     // builds nothing until a banner is ready
const MessageInbox(placement: 'inbox');         // a list; put it on its own screen
const AppMessagesDebugView();                   // the install id, for test devices

What it does

  • One decide per session. A session starts at configure, on identify of another user, and on coming back to the foreground after sessionTimeout (30 minutes). Each one makes one POST /sdk/v1/decide for every configured placement. The widgets serve from its answer, so showing a banner on ten screens is still one call.
    • setConsent('in_app', true) and AppMessages.refresh() decide once more on purpose.
    • The service’s per-install bucket holds 5 decides and refills 1 every 180 s. On a 429 the SDK waits out retry_after and keeps the last decision until then. Offline also keeps it.
    • The decide sends X-App-Key and X-App-Install (the SDK’s random install id), and the reports queued so far go first, so the caps and the popup gap count them.
  • The decision token. Each decide’s token is kept on the device for its user and sent back on the next decide, so the service can reuse its choices without running the rules again. A different user never sends another user’s token.
  • Images are cached before a message counts as ready. A decision’s pictures (its media, a video’s poster, each page’s) are loaded into Flutter’s image cache and kept alive there while the message can show. A video is fetched ahead too, but a message never waits on one.
    • An image that fails (offline, a 404, a timeout of 10 s) means that message is skipped this session. It is never shown broken.
    • There is no disk cache of the SDK’s own. Decisions live in memory for the session, and an offline cold start makes no decide at all, so there would be nothing to show from a disk. To get images that survive a restart, pass a disk-caching provider as imageProvider.
  • The presenter queue. A ready popup (a dialog) or inapp (a full-screen page) waits in a queue until an AppMessagesScope is mounted, its navigator exists, and the app is in the foreground. It is never dropped for being early, such as when the app starts in the background or the decide answers before the first frame. Only one shows at a time; when it closes, the next one comes. A popup shown this session is not shown again this session.
    • A newer decide’s answer for a placement replaces its waiting popup, or withdraws it when the answer is null.
    • The service already returns at most one popup per decide and enforces the org’s popup gap.
  • The inbox. The service answers one message per placement per decide. So the inbox is what the decides handed this user over time: every inbox_card decision is kept on the device, newest first, for 30 days, at most 50 cards.
    • Opening a card marks it read and reports a click. Deleting one reports a dismissal and removes it.
    • Read state is local to the device.
    • The inbox belongs to one user: identifying someone else, or reset(), empties it.
    • A card whose image isn’t cached (offline) is left out of the list until it is.
    • AppMessages.inbox (a ValueListenable) and unreadCount are there for a badge or for an inbox of the app’s own.
  • Headless. To draw messages yourself, use AppMessages.decide() (the ready messages, deciding first if the session hasn’t), AppMessages.messages (a stream of them) and messageFor. Report what happened with reportImpression/Click/Dismiss(messageId). Pass presentPopups: false so the scope leaves popups to you.
  • Reporting. An impression is reported when the message is actually laid out. A click comes from the call to action; the link goes to your onOpenUrl. A dismissal comes from closing it.
    • Each event gets a client uuid (v4) when it happens, so a resent batch counts once.
    • Events are queued on the device (at most 500, for 7 days) and sent in batches of 50 to POST /sdk/v1/events, with X-App-Install on every call. Offline or a 429 keeps them, with a back-off.
    • Each kind is reported once per message per session.
  • track and consent go through the profiles service with the profile’s own key: AppMessages.track('cart_viewed', {'items': 2}), AppMessages.setConsent('in_app', true). Consent is strict: a user who never granted in_app gets nothing from decide, and that includes all audiences.
  • Push. The SDK never registers a push handler, so it can’t fight firebase_messaging or flutter_local_notifications for one. It owns no notification channel and shows no notification.
    • The org’s server gets push_data ({reach_message_id, reach_placement}) from /server/v1/decide and copies it into the FCM message’s data unchanged.
    • When the user opens a notification, your code passes its data map to AppMessages.handlePush(data). That can come from FirebaseMessaging.onMessageOpenedApp, getInitialMessage(), or the payload your flutter_local_notifications tap handler carries.
    • A push reach decided carries reach_message_id: the SDK reports the click and calls onPushOpened(messageId, placement), then returns true. Any other push returns false and is left alone.
    • A push handed over before configure (a launch from the notification) waits for it.
    • With nobody identified, the host still gets the callback, but no click is reported (the service needs the user).
    • Push decisions on the SDK path have push_data: null and are never drawn as widgets.
  • Test devices. AppMessagesDebugView shows the install id. The org registers the tester’s user id and that install id in the panel → Test devices. A test device gets the org’s test drafts, each marked with a small “Test” badge (AppMessage.test). The tester grants in_app consent like anyone.
  • Language. Decides ask for language (en or ar; by default the device’s language). An app with its own language switch calls AppMessages.setLanguage('ar'), which decides once more in that language (while the service asks the app to wait, the last variant stays until retry_after). The message’s own texts run in its dir. The SDK’s few words, such as Close and Test, follow the app’s locale.

Formats

A message can be one of the shopping-app formats. Each is drawn from its own slot in the app’s design, so a new campaign needs no release of the app.

Format Where it shows What the SDK does on the device
splash full screen, at launch skip shown after skip_after_seconds, closed after duration_seconds
stories StoriesRow (or MessageBanner): a row of rings a tap opens the viewer; each page seen is reported (below)
carousel, countdown, coupon, check-in MessageBanner the pages move by themselves; the countdown ticks
popup over the app centre, bottom sheet or full screen; close_after_seconds
lucky draw over the app the wheel turns to what the service drew; a scratch card reveals it
floating button over the app at its position, dragged where the user puts it
toast top of the app a few seconds, once a session

A stories row

Set the placement’s Shown at once (max_shown) above 1 in the portal, and every live story there comes in one decide, best first. Draw them as a row of circles:

const StoriesRow(placement: 'home_stories');   // or MessageBanner(placement: 'home_stories')
  • A story the user hasn’t seen has a coloured ring; a seen one is grey and moves to the end of the row. What was seen is kept on the device, per user. In Arabic the row starts at the right.
  • A tap opens the viewer at that story. Each page has a progress bar and runs its time (a video page, its video). Tap the end side for the next page and the start side for the one before. Hold to pause, swipe to the next or previous story (mirrored in Arabic), and swipe down to close.
  • A story counts an impression when it opens (not when its ring draws), a page view per page, and a click for a page’s link (handed to onOpenUrl). So give stories their own frequency cap, or the org’s cap runs out on one row.
  • The rings take the design’s stories_row look: the unseen gradient, the seen grey, the size.

The server decides every claim, play and check-in: the code, the prize, the streak. The SDK only asks, then draws the view the service sends back with the result.

await AppMessages.event('add_to_cart');   // messages set to show when this happens
await AppMessages.screen('checkout');     // or when this screen opens
await AppMessages.reportConversion(id);   // the user did what the message asked

// The install's push token, from firebase_messaging or the APNs callback:
await AppMessages.setPushToken(token, provider: 'fcm', platform: 'android');
await AppMessages.clearPushToken();       // on sign-out

Videos play in the app’s own player: pass videoPlayer (for example one built on video_player) and precacheVideo in the options. Without a player, a video shows its poster.

Develop

The shared core (../core) is a dependency (heysada_core when shipped). The view renderer, lib/src/ui/, is copied in by python3 ../build.py vendor and git-ignored.

python3 ../build.py vendor && flutter test

test/wire_test.dart is the drift gate against services/nida-inapp/openapi.json. The device run is apps/demo-flutter.

The app’s design (ADR 031, task 419)

Every message (banners, popups, full-screen messages and inbox cards) is drawn from its view with the app’s design bundle (GET /sdk/v1/design/bundle, kept with its ETag, read when a decide names a newer design and again when a view shows a minute after the last read). Its cta reports the click and hands the message’s link to onOpenUrl; dismiss (an inbox card’s delete) reports the dismissal and closes it. A message without a view, or before the bundle arrives, is not shown: the design is the only way a message looks.