=============== LIBRARY RULES =============== From library maintainers: - Run supabase/in_app_messaging.sql once, in the SQL editor or as a migration, before using the client; run it again after upgrading the package. - Call InAppMessaging.initialize once at startup with the Supabase client, the app version, the navigator key that MaterialApp uses and an onUrl callback. It fetches in the background and fires app_open by itself. - Campaigns are rows in iam_campaigns, edited in Supabase Studio or with service_role. A new campaign has active set to false. Clients cannot read the tables: they only call iam_campaigns_for and iam_track. - Call trigger with an event name to show the highest priority campaign whose trigger_events contain it. Caps per campaign are max_impressions, min_interval and stop_after_click; there are none by default. - The audience everyone, signed_in or users reads the request JWT. platforms, min_app_version and max_app_version are claimed by the client, so they target and do not protect. - In tests, use FakeInAppMessaging from package:supabase_in_app_messaging/testing.dart instead of a Supabase client. ### Generate platform runners and run the example Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/example/README.md Run these commands from the example/ directory to create platform runners (--empty preserves lib/main.dart and adds no test) and then launch the app. ```sh flutter create --empty --platforms=android,ios,web . ``` ```sh flutter run ``` -------------------------------- ### Create migration with curl and supabase CLI Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/getting-started.md Downloads the SQL file from the repository and creates a new migration. Replace 'main' with the release tag (e.g., v0.1.0). Then push to the linked project or apply to the local database. ```bash curl -fsSL https://raw.githubusercontent.com/Franklyn-R-Silva/supabase_in_app_messaging/main/supabase/in_app_messaging.sql \ | supabase migration new in_app_messaging supabase db push # the linked project supabase migration up # or the local database ``` -------------------------------- ### Test campaign query with iam_campaigns_for Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/getting-started.md Verifies the database setup by querying campaigns with an empty context. With no campaigns yet, the result is an empty array. ```sql select iam_campaigns_for('{}'); -- [] ``` -------------------------------- ### SQL: Onboarding tip campaign Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md Inserts a banner campaign that shows once on the first screen. Triggered by the 'home_shown' event, with max_impressions set to 1. Requires the database setup and the InAppMessaging instance from initialize. ```sql insert into iam_campaigns (layout, title, body, buttons, trigger_events, max_impressions, active) values ( 'banner', 'Swipe to finish a task', 'Swipe a task to the left to mark it done.', '[{"text": "Got it", "action": "dismiss"}]', '{home_shown}', 1, true ); ``` -------------------------------- ### Example campaign JSON response Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/campaigns.md Example of the JSON array returned by iam_campaigns_for. Contains only rendering data; audience, starts_at, priority, active, and translations stay on the server. Includes caps and ends_at for client-side enforcement. ```json [ { "id": "6f1c2a54-2d0e-4a39-9a51-8f0b1d6e7c10", "layout": "card", "title": "Summer sale", "body": "Everything 20% off this week.", "image_url": "https://example.com/sale.png", "buttons": [ {"text": "Shop now", "action": "url", "url": "myapp://store"}, {"text": "Not now", "action": "dismiss"} ], "trigger_events": ["app_open", "purchase_done"], "ends_at": "2026-12-31T23:59:59+00:00", "max_impressions": 3, "min_interval_seconds": 86400, "stop_after_click": true } ] ``` -------------------------------- ### Dart: Trigger onboarding tip on first screen Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md Fires the 'home_shown' event after fetch completes. The comment explains that on first launch campaigns may not be loaded yet, and fetch() shares the request started by initialize. The trigger is dropped if campaigns haven't arrived. ```dart class _HomePageState extends State { @override void initState() { super.initState(); // On the very first launch the campaigns may still be on their way, and a // trigger before they arrive is dropped. fetch() shares the request // initialize started. messaging.fetch().whenComplete(() { if (mounted) messaging.trigger('home_shown'); }).ignore(); } // ... } ``` -------------------------------- ### Import supabase_in_app_messaging Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/getting-started.md Imports the package in Dart code. ```dart import 'package:supabase_in_app_messaging/supabase_in_app_messaging.dart'; ``` -------------------------------- ### Button JSON examples Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/campaigns.md Each button is a JSON object with text and action. A url action includes a url; any button closes the message and a url button hands its url to the app. Unknown keys or actions are rejected. ```json {"text": "Shop now", "action": "url", "url": "myapp://store"} ``` ```json {"text": "Not now", "action": "dismiss"} ``` -------------------------------- ### Initialize InAppMessaging in Flutter app Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/getting-started.md Sets up the client with a navigator key and starts the app. The campaign's trigger_events default to 'app_open', so the card shows on launch. Keep the InAppMessaging instance to fire custom events with 'trigger'. ```dart import 'package:flutter/material.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_in_app_messaging/supabase_in_app_messaging.dart'; import 'package:url_launcher/url_launcher.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Supabase.initialize( url: 'https://.supabase.co', publishableKey: '', ); final navigatorKey = GlobalKey(); await InAppMessaging.initialize( Supabase.instance.client, appVersion: '1.4.0', // from package_info_plus or your build config navigatorKey: navigatorKey, onUrl: (url) => launchUrl(Uri.parse(url)), ); runApp(MaterialApp(navigatorKey: navigatorKey, home: const HomePage())); } ``` -------------------------------- ### InAppMessaging.initialize Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Initializes the InAppMessaging client with the Supabase client and required configuration. It loads persisted state and starts the first fetch in the background, returning without waiting for the network. ```APIDOC ## InAppMessaging.initialize ### Description Initializes the InAppMessaging client with the Supabase client and required configuration. It loads persisted state and starts the first fetch in the background, returning without waiting for the network. ### Method initialize ### Parameters #### Parameters - **client** (SupabaseClient) - Required - The client that calls `iam_campaigns_for`. Its signed-in user decides which campaigns come back. - **appVersion** (String) - Required - Sent to the database as `app_version`, for campaigns with a minimum or maximum app version. From `package_info_plus` or your build config. - **navigatorKey** (GlobalKey) - Required - The key your `MaterialApp` uses. Messages are shown on its navigator. - **onUrl** (ValueChanged?) - Optional - Called with the url of a url button the user tapped. Your app opens it. - **builder** (InAppMessageBuilder?) - Optional - Replaces the content of any layout, as in `showInAppMessage`. Return null to keep the default for a message. - **shouldShow** (bool Function(InAppMessage)?) - Optional - Return false to refuse a message. See [Vetoing a message](#vetoing-a-message). ### Response #### Success Response Returns an instance of `InAppMessaging`. ### Request Example ```dart final navigatorKey = GlobalKey(); final messaging = await InAppMessaging.initialize( Supabase.instance.client, appVersion: '1.4.0', navigatorKey: navigatorKey, onUrl: (url) => launchUrl(Uri.parse(url)), ); runApp(MaterialApp(navigatorKey: navigatorKey, home: const HomePage())); ``` ``` -------------------------------- ### shouldShow Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Callback called with each campaign that matches the event, in priority order, until one is accepted. Return false to refuse a message, for example an upgrade offer to someone who already upgraded. A refused campaign is skipped, and the next one for the event is offered. ```APIDOC ## shouldShow ### Description Callback called with each campaign that matches the event, in priority order, until one is accepted. Return false to refuse a message. A refused campaign is skipped, and the next one for the event is offered. ### Method Callback ### Parameters - **message** (object) - Required - The campaign message to evaluate. ### Request Example ```dart shouldShow: (message) => !(isPro && message.id == upgradeCampaignId), ``` ``` -------------------------------- ### Initialize InAppMessaging with Supabase client Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Call in an async main before runApp. It loads persisted state from shared_preferences, starts the first fetch in the background, and never throws. Keep the returned instance and pass it where needed. ```dart final navigatorKey = GlobalKey(); final messaging = await InAppMessaging.initialize( Supabase.instance.client, appVersion: '1.4.0', navigatorKey: navigatorKey, onUrl: (url) => launchUrl(Uri.parse(url)), ); runApp(MaterialApp(navigatorKey: navigatorKey, home: const HomePage())); ``` -------------------------------- ### Add supabase_in_app_messaging package Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Install the package with flutter pub add. This is the first step to use the in-app messaging functionality. ```sh flutter pub add supabase_in_app_messaging ``` -------------------------------- ### SQL: Update prompt campaign for Android Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md Inserts a modal campaign for Android users below 2.10.0, shown on app open until they update. High priority puts it before other app_open campaigns. It shows on every start and resume; set min_interval to limit frequency. ```sql insert into iam_campaigns (layout, title, body, buttons, platforms, max_app_version, priority, active) values ( 'modal', 'Update available', 'This version will stop working soon. Update to keep going.', '[{"text": "Update", "action": "url", "url": "https://play.google.com/store/apps/details?id=com.example.app"}, {"text": "Not now", "action": "dismiss"}]', '{android}', '2.10.0', 100, true ); ``` -------------------------------- ### messagesSuppressed Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Sets or gets whether messages are suppressed. When suppressed, any triggered messages are dropped rather than shown later. Both start unsuppressed on every launch, and a message already on screen stays. ```APIDOC ## messagesSuppressed ### Description Sets or gets whether messages are suppressed. When suppressed, any triggered messages are dropped rather than shown later. Both start unsuppressed on every launch, and a message already on screen stays. ### Method messagesSuppressed ### Parameters - **value** (bool) - Required - The suppression state to set. ### Example ```dart messaging.messagesSuppressed = true; ``` ``` -------------------------------- ### messagesSuppressed Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Gets or sets whether messages are suppressed. Setting to true suppresses messages. ```APIDOC ## messagesSuppressed ### Description Gets or sets whether messages are suppressed. Setting to true suppresses messages. ### Method messagesSuppressed (property) ### Parameters - **value** (bool) - Required - Set to true to suppress messages. ### Returns - **bool** - The current suppression state. ``` -------------------------------- ### Suppressing messages: Firebase setMessagesSuppressed vs supabase messagesSuppressed Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Shows the Firebase and supabase_in_app_messaging equivalents for suppressing in-app messages. Both drop messages triggered while suppressed (not queued) and start unsuppressed on every launch; a message already on screen stays. `shouldShow:` in `initialize` provides finer control by vetoing individual campaigns. ```dart // Firebase await FirebaseInAppMessaging.instance.setMessagesSuppressed(true); ``` ```dart // supabase_in_app_messaging messaging.messagesSuppressed = true; ``` -------------------------------- ### Dart: Handle rating prompt URL Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md In the initialize onUrl callback, opens the store review for the 'myapp://rate' URL, otherwise launches the URL. The comment suggests using the in_app_review package for the store review. ```dart // In initialize: onUrl: (url) { if (url == 'myapp://rate') { openStoreReview(); // for example with the in_app_review package } else { launchUrl(Uri.parse(url)); } }, ``` -------------------------------- ### Initialize InAppMessaging and run app Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Initialize the messaging client with Supabase client, app version, navigator key, and URL handler. Then run the app with the navigator key. ```dart final navigatorKey = GlobalKey(); final messaging = await InAppMessaging.initialize( Supabase.instance.client, appVersion: '1.4.0', // from package_info_plus or your build config navigatorKey: navigatorKey, onUrl: (url) => launchUrl(Uri.parse(url)), // url_launcher, or your router ); runApp(MaterialApp(navigatorKey: navigatorKey, home: const HomePage())); ``` -------------------------------- ### Dart: Initialize with app version and URL handler for update prompt Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md In the initialize call, sets appVersion from package_info_plus and onUrl to launch URLs. The comment references the same appVersion as above. ```dart // In initialize: appVersion: info.version, // from package_info_plus, as above onUrl: (url) => launchUrl(Uri.parse(url)), ``` -------------------------------- ### fetch() Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Fetches the campaigns again. It calls iam_campaigns_for with the current context, caches the campaigns, warms images, and sends pending events. It throws on failure and keeps previously fetched or cached campaigns. ```APIDOC ## fetch() ### Description Fetches the campaigns again. It calls `iam_campaigns_for` with the current context, caches the campaigns, warms images, and sends pending events. It throws on failure and keeps previously fetched or cached campaigns. ### Method fetch ### Returns `Future` ### Errors - `PostgrestException` when the database rejects the call - network error, such as `ClientException` or `SocketException` - `AuthException` when the session has expired and cannot be refreshed - `TimeoutException` after 30 seconds - `FormatException` when the response is not a JSON array ### Request Example ```json {"platform": "android", "app_version": "1.4.0", "locale": "pt-BR"} ``` ``` -------------------------------- ### Query campaigns with iam_campaigns_for Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/campaigns.md Call iam_campaigns_for with a JSON context containing platform, app_version, and locale to retrieve campaigns for the current user. Returns a JSON array ordered by priority and starts_at. ```sql select iam_campaigns_for('{"platform": "android", "app_version": "2.10.0", "locale": "en-US"}'); ``` -------------------------------- ### trigger(event) Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Shows the campaign for the given event, if there is one. The event is a string identifier that matches a campaign trigger. ```APIDOC ## trigger(event) ### Description Shows the campaign for the given event, if there is one. The event is a string identifier that matches a campaign trigger. ### Method trigger ### Parameters - **event** (string) - Required - The event name to trigger a campaign. ``` -------------------------------- ### messaging.initialize Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Initializes the messaging client. The `shouldShow` callback can veto a campaign, allowing the next campaign for the event to be offered. ```APIDOC ## messaging.initialize ### Description Initializes the messaging client. The `shouldShow` callback can veto a campaign, allowing the next campaign for the event to be offered. ### Parameters - **shouldShow** (function) - Optional - A callback that receives a campaign and returns a boolean indicating whether to show it. ### Notes - `app_open` fires automatically after the first fetch and each time the app returns from the background. ``` -------------------------------- ### Dart: Initialize with app version for feature announcement Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md Initializes InAppMessaging with the real app version from package_info_plus. The app needs nothing beyond this because trigger_events defaults to app_open, which fires automatically. ```dart final info = await PackageInfo.fromPlatform(); // package_info_plus final messaging = await InAppMessaging.initialize( Supabase.instance.client, appVersion: info.version, navigatorKey: navigatorKey, onUrl: openUrl, ); ``` -------------------------------- ### trigger(event) Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Shows the first campaign, in priority order, whose trigger events include the given event and whose ends_at has not passed, with showInAppMessage on your navigator. The event is dropped rather than queued under certain conditions such as no matching campaign, a message already on screen, messagesSuppressed being true, frequency cap reached, shouldShow refusing, or navigator not mounted. ```APIDOC ## trigger(event) ### Description Shows the first campaign, in priority order, whose trigger events include the given event and whose ends_at has not passed, with showInAppMessage on your navigator. ### Method trigger ### Parameters - **event** (string) - Required - The event name to trigger. ### Request Example ```dart messaging.trigger('purchase_done'); ``` ``` -------------------------------- ### dispose() Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Stops watching sign-ins and the app lifecycle, leaves the Realtime channel, and drops the campaigns. Call this when the client is no longer needed. ```APIDOC ## dispose() ### Description Stops watching sign-ins and the app lifecycle, leaves the Realtime channel, and drops the campaigns. Call this when the client is no longer needed. ### Method dispose ### Returns `void` ``` -------------------------------- ### iam_campaigns_for Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/campaigns.md Returns campaigns that match the given context. The function takes a JSON object with platform, app_version, and locale, and returns a JSON array of campaigns sorted by priority. ```APIDOC ## iam_campaigns_for ### Description Returns campaigns that match the given context. The function takes a JSON object with platform, app_version, and locale, and returns a JSON array of campaigns sorted by priority. ### Method Function ### Endpoint iam_campaigns_for(p_context) ### Parameters #### Request Body - **p_context** (json) - Required - A JSON object containing the context: `platform`, `app_version`, and `locale`. ### Response #### Success Response Returns a JSON array of campaigns, each with fields like `id`, `layout`, `title`, `body`, `image_url`, `buttons`, `trigger_events`, `ends_at`, `max_impressions`, `min_interval_seconds`, and `stop_after_click`. ### Request Example ```sql select iam_campaigns_for('{"platform": "android", "app_version": "2.10.0", "locale": "en-US"}'); ``` #### Response Example ```json [ { "id": "6f1c2a54-2d0e-4a39-9a51-8f0b1d6e7c10", "layout": "card", "title": "Summer sale", "body": "Everything 20% off this week.", "image_url": "https://example.com/sale.png", "buttons": [ {"text": "Shop now", "action": "url", "url": "myapp://store"}, {"text": "Not now", "action": "dismiss"} ], "trigger_events": ["app_open", "purchase_done"], "ends_at": "2026-12-31T23:59:59+00:00", "max_impressions": 3, "min_interval_seconds": 86400, "stop_after_click": true } ] ``` ``` -------------------------------- ### SQL: New feature announcement campaign Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md Inserts a card campaign for app open, targeting versions 2.10.0 to 3.0.0 (exclusive), once, until end of January. trigger_events defaults to app_open, which fires automatically after first fetch and on resume. ```sql insert into iam_campaigns (layout, title, body, image_url, buttons, min_app_version, max_app_version, max_impressions, ends_at, active) values ( 'card', 'New: dark mode', 'Turn it on in Settings, Appearance.', 'https://.supabase.co/storage/v1/object/public/iam/dark-mode.png', '[{"text": "Try it", "action": "url", "url": "myapp://settings/appearance"}, {"text": "Later", "action": "dismiss"}]', '2.10.0', '3.0.0', 1, '2027-02-01', true ); ``` -------------------------------- ### Insert campaign and query campaigns for a user in SQL Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Insert a campaign row with layout, audience, platforms, version constraints, and schedule. The select uses iam_campaigns_for with a JSON argument representing the user's platform and app version; it returns matching campaigns. Note that in the SQL editor nobody is signed in, so the campaign is excluded. ```sql -- Only signed-in Android users on 2.10.0 or later, for December. insert into iam_campaigns (layout, title, body, audience, platforms, min_app_version, starts_at, ends_at, priority, active) values ('banner', 'Dark mode is here', 'Turn it on in Settings.', 'signed_in', '{android}', '2.10.0', '2026-12-01', '2027-01-01', 10, true); ``` ```sql -- What a signed-in Android app on 2.10.0 gets. In the SQL editor nobody is -- signed in, so this campaign is left out there. select iam_campaigns_for('{"platform": "android", "app_version": "2.10.0"}'); -- [{"id": "…", "layout": "banner", "title": "Dark mode is here", …}] ``` -------------------------------- ### Widget test with FakeInAppMessaging Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Use FakeInAppMessaging from package:supabase_in_app_messaging/testing.dart to test in-app messaging without Supabase. It does not export the main library, so import both. The fake uses the same trigger rules as the real client and records events; call trigger('app_open') manually since nothing fires by itself. ```dart import 'package:supabase_in_app_messaging/supabase_in_app_messaging.dart'; import 'package:supabase_in_app_messaging/testing.dart'; testWidgets('a purchase asks for a rating', (tester) async { final navigatorKey = GlobalKey(); final opened = []; final messaging = FakeInAppMessaging( navigatorKey: navigatorKey, onUrl: opened.add, messages: const [ InAppMessage( id: 'rate', layout: InAppMessageLayout.modal, title: 'Enjoying it?', buttons: [InAppMessageButton(text: 'Rate', url: 'store://rate')], triggerEvents: ['purchase_done'], ), ], ); await tester.pumpWidget(MyApp(messaging: messaging, navigatorKey: navigatorKey)); messaging.trigger('purchase_done'); await tester.pumpAndSettle(); await tester.tap(find.text('Rate')); await tester.pumpAndSettle(); expect(opened, ['store://rate']); expect(messaging.events, [ (campaignId: 'rate', kind: 'impression'), (campaignId: 'rate', kind: 'click'), ]); }); ``` -------------------------------- ### Trigger campaign event Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Show a campaign when the app fires an event, such as 'purchase_done'. ```dart messaging.trigger('purchase_done'); ``` -------------------------------- ### InAppMessaging.initialize Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Initializes the Supabase In-App Messaging SDK. Returns an instance that you keep and pass around. The same navigatorKey must be passed to MaterialApp. ```APIDOC ## InAppMessaging.initialize ### Description Initializes the Supabase In-App Messaging SDK. Returns an instance that you keep and pass around. The same navigatorKey must be passed to MaterialApp. ### Method initialize ### Parameters - **client** (SupabaseClient) - Required - The Supabase client instance. - **appVersion** (optional) - Optional - The app version. - **navigatorKey** (GlobalKey) - Required - The navigator key used by MaterialApp. ### Returns - **InAppMessaging** - The initialized instance. ``` -------------------------------- ### Show an in-app message with showInAppMessage Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/widgets.md Displays the message and completes with the tapped button or null on dismissal. The onUrl callback receives the URL of a tapped url button; the package does not open URLs itself. ```dart final tapped = await showInAppMessage( context, message, onUrl: (url) => launchUrl(Uri.parse(url)), ); ``` -------------------------------- ### showInAppMessage Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/widgets.md Displays an in-app message and returns the button tapped or null if dismissed. Supports custom theming and a builder for custom layouts. ```APIDOC ## showInAppMessage ### Description Displays an in-app message and returns the button tapped or null if dismissed. Supports custom theming and a builder for custom layouts. ### Method `showInAppMessage` ### Parameters - `context` (BuildContext) - Required - The build context. - `message` (InAppMessage) - Required - The message to display. - `onUrl` (void Function(Uri)?) - Optional - Called when a URL button is tapped. - `builder` (Widget? Function(BuildContext, InAppMessage, void Function(InAppMessageButton?))?) - Optional - Replaces the content of any layout; return null to keep the default. ### Returns `Future` - The button the user tapped, or null if dismissed. ### Request Example ```dart final tapped = await showInAppMessage( context, message, onUrl: (url) => launchUrl(Uri.parse(url)), ); ``` ### Builder Example ```dart showInAppMessage( context, message, builder: (context, message, close) => message.layout == InAppMessageLayout.banner ? MyBanner(message, onTap: () => close(message.buttons.firstOrNull)) : null, ); ``` ``` -------------------------------- ### Veto a message with shouldShow Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md shouldShow is called with each campaign that matches the event, in priority order, until one is accepted. Return false to refuse a message, e.g., an upgrade offer to someone who already upgraded. A refused campaign is skipped and the next one for the event is offered. ```dart shouldShow: (message) => !(isPro && message.id == upgradeCampaignId), ``` -------------------------------- ### messagesSuppressed Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md A boolean property that, while true, prevents any messages from being shown. Set it to suppress or allow message display. ```APIDOC ## messagesSuppressed ### Description A boolean property that, while true, prevents any messages from being shown. Set it to suppress or allow message display. ### Type `bool` ``` -------------------------------- ### Show In-App Message with onUrl callback Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Displays an in-app message and returns a Future that completes when the message is dismissed. The onUrl callback handles URL taps. ```dart final tapped = await showInAppMessage(context, message, onUrl: openUrl); ``` -------------------------------- ### Query iam_campaign_stats for last 30 days Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/metrics.md Retrieves campaign statistics for the last 30 days, joining with campaign titles. The view sums impressions, clicks, and dismissals per campaign and day for signed-in users only. ```sql select c.title, s.* from iam_campaign_stats s join iam_campaigns c on c.id = s.campaign_id where s.day > current_date - 30 order by s.day desc, c.title; ``` -------------------------------- ### Insert campaign into iam_campaigns table Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Add a campaign to the iam_campaigns table. The SQL is re-runnable and should be run once per Supabase project. ```sql insert into iam_campaigns (layout, title, body, buttons, active) values ( 'card', 'Summer sale', 'Everything 20% off this week.', '[{"text": "Shop now", "action": "url", "url": "myapp://store"}, {"text": "Not now", "action": "dismiss"}]', true ); ``` -------------------------------- ### Track events with iam_track in SQL editor Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/metrics.md Sends a batch of events as the signed-in user. In the SQL editor, where no user is signed in, this call fails because user_id is null. Only authenticated users may call iam_track, and only as themselves. ```sql select iam_track('[ {"campaign_id": "", "kind": "impression", "at": 1764756000000}, {"campaign_id": "", "kind": "click", "at": 1764756004000} ]'); ``` -------------------------------- ### SQL: Rating prompt campaign Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md Inserts a modal campaign triggered after purchase, at most every 30 days, and stops after the user clicks 'Rate it'. The 'Not now' button is a dismissal, so it can reappear after 30 days. ```sql insert into iam_campaigns (layout, title, body, buttons, trigger_events, min_interval, stop_after_click, active) values ( 'modal', 'Enjoying the app?', 'A rating helps other people find it.', '[{"text": "Rate it", "action": "url", "url": "myapp://rate"}, {"text": "Not now", "action": "dismiss"}]', '{purchase_done}', '30 days', true, true ); ``` -------------------------------- ### Customize layout with builder Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/widgets.md Replaces the content of any layout. Return null to keep the default for a message. The close callback accepts the tapped button or null to dismiss; a second call is ignored. ```dart showInAppMessage( context, message, builder: (context, message, close) => message.layout == InAppMessageLayout.banner ? MyBanner(message, onTap: () => close(message.buttons.firstOrNull)) : null, ); ``` -------------------------------- ### Suppress messages with messagesSuppressed in initState and dispose Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/client-api.md Set messaging.messagesSuppressed to true on screens that must not be interrupted (e.g., checkout or video) and clear it when leaving. A message already on screen stays. ```dart @override void initState() { super.initState(); messaging.messagesSuppressed = true; } @override void dispose() { messaging.messagesSuppressed = false; super.dispose(); } ``` -------------------------------- ### Customize In-App Message Layout with Builder Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Replaces the content of any layout using the builder parameter. Returning null keeps the default content for that message. The builder receives the context, message, and a close function. ```dart showInAppMessage( context, message, builder: (context, message, close) => message.layout == InAppMessageLayout.banner ? MyBanner(message, onTap: () => close(message.buttons.firstOrNull)) : null, // null keeps the default for this message ); ``` -------------------------------- ### Update iam_campaigns to set frequency caps Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/frequency-caps.md Sets max_impressions, min_interval, and stop_after_click for a campaign. The caps apply per user: max_impressions limits total impressions, min_interval enforces a minimum time between impressions, and stop_after_click prevents further impressions after a click. ```sql -- Once a day, at most three times, and never again after "Shop now". update iam_campaigns set max_impressions = 3, min_interval = '1 day', stop_after_click = true where title = 'Summer sale'; ``` -------------------------------- ### SQL update for translations Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/campaigns.md Updates the translations column of iam_campaigns with a JSON object keyed by BCP 47 language tags. Each entry may set title, body, and buttons (in order). The check constraint rejects invalid keys, duplicate tags, unknown fields, blank titles, or mismatched button counts. ```sql update iam_campaigns set translations = '{ "pt-BR": {"title": "Promoção de verão", "body": "Tudo com 20% de desconto.", "buttons": ["Comprar", "Agora não"]}, "es": {"title": "Rebajas de verano", "buttons": ["Comprar", "Ahora no"]} }' where title = 'Summer sale'; ``` -------------------------------- ### Parse a campaign with InAppMessage.tryParse Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/widgets.md Parses one element of the array returned by iam_campaigns_for. Never throws; returns null when the message cannot be shown (e.g., missing id/title or unknown layout). ```dart final message = InAppMessage.tryParse(json); ``` -------------------------------- ### Count unique users over a range from iam_events Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/metrics.md Counts distinct users who saw a campaign in the last 30 days. Use this instead of summing unique_users from iam_campaign_stats, which counts a user on each day they were shown the campaign. ```sql select count(distinct user_id) from iam_events where campaign_id = '' and kind = 'impression' and created_at > now() - interval '30 days'; ``` -------------------------------- ### InAppMessage.tryParse Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/widgets.md Parses a JSON object from the iam_campaigns_for array into an InAppMessage. Returns null if the message cannot be shown by this version. ```APIDOC ## InAppMessage.tryParse ### Description Parses a JSON object from the `iam_campaigns_for` array into an `InAppMessage`. Returns null if the message cannot be shown by this version. ### Method `InAppMessage.tryParse` ### Parameters - `json` (dynamic) - Required - One element of the array `iam_campaigns_for` returns. ### Returns `InAppMessage?` - The parsed message, or null if the JSON is not an object, missing `id` or `title`, or has an unknown `layout`. ### Request Example ```dart final message = InAppMessage.tryParse(json); ``` ``` -------------------------------- ### iam_campaigns_for response with caps Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/frequency-caps.md Shows the JSON returned by iam_campaigns_for, including max_impressions, min_interval_seconds (in seconds), and stop_after_click. The interval is converted to seconds. ```json {"max_impressions": 3, "min_interval_seconds": 86400, "stop_after_click": true} ``` -------------------------------- ### SQL: Query impressions, clicks, and dismissals from iam_events Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Reads per-campaign counts of impressions, clicks, and dismissals for signed-in users from iam_events, joining with iam_campaigns. Use in the SQL editor or as service_role; signed-out users send no events and are not counted. ```sql select c.title, count(e.id) filter (where e.kind = 'impression') as impressions, count(e.id) filter (where e.kind = 'click') as clicks, count(e.id) filter (where e.kind = 'dismiss') as dismissals from iam_campaigns c left join iam_events e on e.campaign_id = c.id group by c.id, c.title order by impressions desc; ``` -------------------------------- ### Dart: Trigger rating prompt after purchase Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/recipes.md Fires the 'purchase_done' event after the order is placed. The comment notes that a trigger while messagesSuppressed is set is dropped, so a checkout screen that suppresses messages lets this one through first. ```dart await placeOrder(); messaging.messagesSuppressed = false; // the order is done messaging.trigger('purchase_done'); ``` -------------------------------- ### Schedule nightly pruning with pg_cron Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/metrics.md Schedules iam_prune_events to run every night at 03:30 using pg_cron. Requires enabling the pg_cron extension in the dashboard. pg_cron is optional; you can call the function manually or from any job with the service_role key. ```sql select cron.schedule('iam-prune-events', '30 3 * * *', 'select public.iam_prune_events()'); ``` -------------------------------- ### Trigger events and suppress messages in Dart Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Use messaging.trigger('purchase_done') to fire an event; the first campaign for the event by priority is shown. Set messaging.messagesSuppressed = true to suppress messages, e.g., during checkout or video playback. Triggers while a message is on screen or suppressed are dropped, not queued. shouldShow: in initialize can veto a campaign. ```dart messaging.trigger('purchase_done'); // the first campaign for the event, by priority messaging.messagesSuppressed = true; // checkout, a video: nothing shows ``` -------------------------------- ### builder Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Replaces the content of any layout with a custom Flutter widget. Impressions, clicks, and dismissals are recorded automatically. ```APIDOC ## builder ### Description Replaces the content of any layout with a custom Flutter widget. Impressions, clicks, and dismissals are recorded automatically. ### Method builder (property) ### Parameters - **builder** (WidgetBuilder) - Required - The widget builder that returns the custom content. ``` -------------------------------- ### SQL: Update campaign audience with users who ordered this month Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Builds a targeting segment from your own tables by setting the campaign's audience to 'users' and populating user_ids with a snapshot of distinct user IDs from the orders table created in the current month. Run the update again to refresh the snapshot; an empty list is rejected because a 'users' audience requires at least one user. ```sql update iam_campaigns set audience = 'users', user_ids = (select array_agg(distinct user_id) from orders where created_at >= date_trunc('month', now())) where title = 'Thanks for shopping'; ``` -------------------------------- ### Triggering a campaign: Firebase triggerEvent vs supabase trigger Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/migrating-from-firebase.md Shows the Firebase and supabase_in_app_messaging equivalents for triggering a campaign on a custom event. In supabase, only `trigger` shows a campaign; `app_open` is the only event fired automatically. A trigger while a message is up or before campaigns arrive is dropped, not queued. ```dart // Firebase await FirebaseInAppMessaging.instance.triggerEvent('purchase_done'); ``` ```dart // supabase_in_app_messaging messaging.trigger('purchase_done'); ``` -------------------------------- ### Prune events with iam_prune_events Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/docs/metrics.md Deletes events older than an interval (default 180 days) and returns the number deleted. Only service_role and postgres may call it. Pruning resets impression and click caps because old events stop counting. ```sql select iam_prune_events(); -- older than 180 days select iam_prune_events(interval '90 days'); ``` -------------------------------- ### messaging.messagesSuppressed Source: https://github.com/franklyn-r-silva/supabase_in_app_messaging/blob/main/README.md Suppresses or re-enables in-app messages. When set to true, no messages are shown; triggers are dropped. Useful during checkout or video playback. ```APIDOC ## messaging.messagesSuppressed ### Description Suppresses or re-enables in-app messages. When set to true, no messages are shown; triggers are dropped. Useful during checkout or video playback. ### Property `messagesSuppressed` (bool) ### Example ```dart messaging.messagesSuppressed = true; ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.