entrig 0.0.5-dev copy "entrig: ^0.0.5-dev" to clipboard
entrig: ^0.0.5-dev copied to clipboard

Entrig Plugin

Entrig #

Push Notifications for Supabase

Send push notifications to your Flutter app, triggered by database events.


Prerequisites #

  1. Create Entrig Account - Sign up at entrig.com

  2. Connect Supabase - Authorize Entrig to access your Supabase project

    How it works (click to expand)

    During onboarding, you'll:

    1. Click the "Connect Supabase" button
    2. Sign in to your Supabase account (if not already signed in)
    3. Authorize Entrig to access your project
    4. Select which project to use (if you have multiple)

    That's it! Entrig will automatically set up everything needed to send notifications. No manual SQL or configuration required.

  3. Upload FCM Service Account (Android) - Upload Service Account JSON and provide your Application ID

    How to get FCM Service Account JSON (click to expand)
    1. Create a Firebase project at console.firebase.google.com
    2. Add your Android app to the project
    3. Go to Project Settings → Service Accounts
    4. Click "Firebase Admin SDK"
    5. Click "Generate new private key"
    6. Download the JSON file
    7. Upload this file to the Entrig dashboard
    What is Application ID? (click to expand)

    The Application ID is your Android app's package name (e.g., com.example.myapp). You can find it in:

    • Your android/app/build.gradle file under applicationId
    • Or in your AndroidManifest.xml under the package attribute

    Note: If you've configured iOS in your Firebase console, you can use FCM for both Android and iOS, which will skip the APNs setup step.

  4. Upload APNs Key (iOS) - Upload .p8 key file with Team ID, Bundle ID, and Key ID to Entrig

    How to get APNs Authentication Key (click to expand)
    1. Enroll in Apple Developer Program
    2. Go to Certificates, Identifiers & Profiles
    3. Navigate to Keys → Click "+" to create a new key
    4. Enter a key name and enable "Apple Push Notifications service (APNs)"
    5. Click "Continue" then "Register"
    6. Download the .p8 key file (you can only download this once!)
    7. Note your Key ID (shown on the confirmation page - 10 alphanumeric characters)
    8. Note your Team ID (found in Membership section of your Apple Developer account - 10 alphanumeric characters)
    9. Note your Bundle ID (found in your Xcode project settings or Info.plist - reverse domain format like com.example.app)
    10. Upload the .p8 file along with Team ID, Bundle ID, and Key ID to the Entrig dashboard
    Production vs Sandbox environments (click to expand)

    Entrig supports configuring both APNs environments:

    • Production: For App Store releases and TestFlight builds
    • Sandbox: For development builds via Xcode

    You can configure one or both environments during onboarding. Developers typically need Sandbox for testing and Production for live releases. You can use the same APNs key for both environments, but you'll need to provide the configuration separately for each.


Installation #

Add Entrig to your pubspec.yaml:

dependencies:
  entrig: ^0.0.2-beta

Platform Setup #

Android #

No setup required for Android. We'll take care of it.

iOS #

Run this command in your project root:

dart run entrig:setup ios

This automatically configures:

  • AppDelegate.swift with Entrig notification handlers
  • Runner.entitlements with push notification entitlements
  • Info.plist with background modes

Note: The command creates .backup files for safety. You can delete them after verifying everything works.

Manual setup (click to expand)

1. Enable Push Notifications in Xcode

  • Open ios/Runner.xcworkspace
  • Select Runner target → Signing & Capabilities
  • Click + Capability → Push Notifications
  • Click + Capability → Background Modes → Enable Remote notifications and Background fetch

2. Update AppDelegate.swift

import Flutter
import UIKit
import entrig
import UserNotifications

@main
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)

        // Setup Entrig notification handling
        UNUserNotificationCenter.current().delegate = self
        EntrigPlugin.checkLaunchNotification(launchOptions)

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    override func application(_ application: UIApplication,
                            didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        EntrigPlugin.didRegisterForRemoteNotifications(deviceToken: deviceToken)
    }

    override func application(_ application: UIApplication,
                            didFailToRegisterForRemoteNotificationsWithError error: Error) {
        EntrigPlugin.didFailToRegisterForRemoteNotifications(error: error)
    }

    // MARK: - UNUserNotificationCenterDelegate
    override func userNotificationCenter(_ center: UNUserNotificationCenter,
                                        willPresent notification: UNNotification,
                                        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        EntrigPlugin.willPresentNotification(notification)
        completionHandler([])
    }

    override func userNotificationCenter(_ center: UNUserNotificationCenter,
                                        didReceive response: UNNotificationResponse,
                                        withCompletionHandler completionHandler: @escaping () -> Void) {
        EntrigPlugin.didReceiveNotification(response)
        completionHandler()
    }
}

Usage #

Initialize #

Initialize Entrig and Supabase in your main():

import 'package:flutter/material.dart';
import 'package:entrig/entrig.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Supabase
  await Supabase.initialize(
    url: 'YOUR_SUPABASE_URL',
    anonKey: 'YOUR_SUPABASE_ANON_KEY',
  );

  // Initialize Entrig with automatic registration (Recommended if using Supabase Auth)
  await Entrig.init(
    apiKey: 'YOUR_ENTRIG_API_KEY',
    autoRegisterWithSupabaseAuth: AutoRegisterWithSupabaseAuth(
      supabaseClient: Supabase.instance.client,
    ),
  );

  runApp(MyApp());
}
How to get your Entrig API key (click to expand)
  1. Sign in to your Entrig account at entrig.com
  2. Go to your dashboard
  3. Navigate to your project settings
  4. Copy your API Key from the project settings page
  5. Use this API key in the Entrig.init() call above

This automatically registers/unregisters devices when users sign in/out with Supabase Auth.

Important: When using autoRegisterWithSupabaseAuth, devices are registered with the Supabase Auth user ID (auth.users.id). When creating notifications, make sure the user identifier field you select contains this same Supabase Auth user ID to ensure notifications are delivered to the correct users.

Manual registration (click to expand)

If you prefer to handle registration manually, initialize without autoRegisterWithSupabaseAuth:

await Entrig.init(apiKey: 'YOUR_ENTRIG_API_KEY');

Then register/unregister manually:

Register device:

final userId = Supabase.instance.client.auth.currentUser?.id;
if (userId != null) {
  await Entrig.register(userId: userId);
}

Unregister device:

await Entrig.unregister();

Note: register() automatically handles permission requests. The userId you pass here must match the user identifier field you select when creating notifications.

Custom Permission Handling:

If you want to handle notification permissions yourself, disable automatic permission handling:

await Entrig.init(
  apiKey: 'YOUR_ENTRIG_API_KEY',
  handlePermission: false,
);

Then request permissions manually using Entrig.requestPermission() before registering.

Listen to Notifications #

Foreground notifications (when app is open):

Entrig.foregroundNotifications.listen((NotificationEvent event) {
  // Handle notification received while app is in foreground
  // Access: event.title, event.body, event.type, event.data
});

Notification tap (when user taps a notification):

Entrig.onNotificationOpened.listen((NotificationEvent event) {
  // Handle notification tap - navigate to specific screen based on event.type or event.data
});

NotificationEvent contains:

  • title - Notification title
  • body - Notification body text
  • type - Optional custom type identifier (e.g., "new_message", "order_update")
  • data - Optional custom payload data from your database

Creating Notifications #

Learn how to create notification triggers in the dashboard (click to expand)

Create notification triggers in the Entrig dashboard. The notification creation form has two sections: configuring the trigger and composing the notification message.

Section 1: Configure Trigger #

Set up when and to whom notifications should be sent.

1. Select Table

Choose the database table where events will trigger notifications (e.g., messages, orders). This is the "trigger table" that activates the notification.

2. Select Event

Choose which database operation triggers the notification:

  • INSERT - When new rows are created
  • UPDATE - When existing rows are modified
  • DELETE - When rows are deleted

3. Select User Identifier

Specify how to identify notification recipients. Toggle "Use join table" to switch between modes.

Important: The user identifier field you select here must contain the same user ID that was used when registering the device. If using autoRegisterWithSupabaseAuth, this should be the Supabase Auth user ID (auth.users.id).

Single User Mode (Default):

  • Select a field that contains the user ID directly
  • Supports foreign key navigation (e.g., navigate through orders.customer_id to reach customers.user_id)
  • Example: For a messages table with user_id field, select user_id
  • The selected field should contain the same user ID used during device registration

Multi-User Mode (Join Table):

  • Use when one database event should notify multiple users

  • Requires configuring the relationship between tables:

    Event Table Section:

    • Lookup Field: Select a foreign key field that links to your join table
      • Example: For notifying all room members when a message is sent, select room_id from the messages table

    Join Table Section:

    • Join Table: Select the table containing recipient records
      • Example: room_members table that links rooms to users
    • Matching Field: Field in the join table that matches your lookup field
      • Usually auto-populated to match the lookup field name
      • Example: room_id in room_members
    • User ID Field: Field containing the actual user identifiers
      • Supports foreign key navigation
      • Example: user_id in room_members
      • Should contain the same user ID used during device registration (e.g., Supabase Auth user ID)

4. Event Conditions (Optional)

Filter when notifications are sent based on the trigger event data:

  • Add conditions to control notification sending (e.g., only when status = 'completed')
  • Supports multiple conditions with AND/OR logic
  • Conditions check the row data from the trigger table

5. Recipient Filters (Optional, Multi-User only)

Filter which users receive the notification based on join table data:

  • Example: Only notify users where role = 'admin' in the join table
  • Different from Event Conditions - these filter recipients, not events

Section 2: Compose Notification #

Design the notification content that users will see.

1. Notification Type (Optional)

Add a custom type identifier for your Flutter app to recognize this notification:

  • Example values: new_message, order_update, friend_request
  • Access via event.type in your notification listeners
  • Use to route users to different screens or handle notifications differently

2. Payload Data (Optional)

Select database fields to use as dynamic placeholders:

  • Click "Add Fields" to open the field selector
  • Selected fields appear as clickable pills (e.g., {{messages.content}})
  • Click any pill to insert it at your cursor position in title or body
  • Supports nested field selection through foreign keys

3. Title & Body

Write your notification text using placeholders:

  • Use double-brace format: {{table.column}}
  • Example Title: New message from {{users.name}}
  • Example Body: {{messages.content}}
  • Placeholders are replaced with actual data when notifications are sent
  • Title appears as the notification headline
  • Body appears as the notification message

What Happens Behind the Scenes #

When you create a notification, Entrig automatically:

  1. Enables pg_net extension in your Supabase project
  2. Creates a PostgreSQL function to send HTTP requests to Entrig
  3. Sets up a database trigger on your selected table
  4. Configures webhook endpoint for your notification

No manual SQL or backend code required!

Example Use Cases #

Single User Notification:

  • Table: orders, Event: INSERT
  • User ID: customer_id
  • Title: Order Confirmed!
  • Body: Your order #{{orders.id}} has been received

Multi-User Notification (Group Chat):

  • Table: messages, Event: INSERT
  • Lookup Field: room_id
  • Join Table: room_members
  • Matching Field in Join Table: room_id
  • User ID: user_id
  • Title: New message in {{messages.room_name}}
  • Body: {{messages.sender_name}}: {{messages.content}}

Support #