> ## Documentation Index
> Fetch the complete documentation index at: https://docs.notifly.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Flutter

> Install the Notifly Flutter SDK, configure iOS and Android, and integrate push notifications and in-app popups.

The Notifly Flutter plugin connects your Flutter app to Notifly.

The SDK supports the following features:

* Register devices with Notifly to receive push notifications and display in-app popups.
  (In-app popups appear only while the app is in the foreground.)
* Send event and user data to Notifly for campaign targeting and analysis.
* Log user behavior as events and measure campaign performance.

> [!NOTE]
>
> In-app popups on Android require **Android 11 (API level 30) or later**.

## Prerequisites

1. **Connect your Firebase project.**\
   The Notifly iOS SDK uses [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) to send push notifications.

> [Connect Firebase](https://docs.notifly.tech/en/developer-guide/firebase-integration.md)

2. **Register your APNs credentials for iOS.**

> [Register APNs credentials](https://docs.notifly.tech/en/developer-guide/firebase-integration.md#1-3-register-an-apns-authentication-key)

> [!NOTE]
>
> * For iOS builds, open `Runner.xcworkspace` in Xcode.

## 1. Set up the plugin

### Install the plugin

```bash theme={null}
flutter pub add notifly_flutter
cd ios && pod install
```

The `flutter pub add` command adds the dependency to `pubspec.yaml`. The badge shows the latest published version. [![Pub](https://img.shields.io/pub/v/notifly_flutter.svg)](https://pub.dev/packages/notifly_flutter)

### Configure iOS

#### 1. Configure capabilities

1. Open `Runner.xcworkspace` in Xcode. Use the workspace rather than `.xcodeproj` to build with the Notifly SDK.

2. Set the target's minimum iOS version to 15.0 or later. Set the same minimum version in your Podfile.

3. Enable **Push Notifications** and **Background Modes**, including **Remote notifications** and **Background fetch**.

   ![Add Capabilities](https://mintcdn.com/notifly/QWigoXWbDguqzkH4/ko/developer-guide/image/ios_setting_add_capability1.png?fit=max\&auto=format\&n=QWigoXWbDguqzkH4\&q=85\&s=53445279fef5364a29715d9a887eff48)

   ![Add Capabilities](https://mintcdn.com/notifly/umP8GQfcNYrXNUqj/ko/developer-guide/image/ios_setting_add_capability2.png?fit=max\&auto=format\&n=umP8GQfcNYrXNUqj\&q=85\&s=aa12e246d24cf9eb015ea2aef2656c09)

#### 2. Configure `AppDelegate.swift`

1. Locate the file.

The Swift AppDelegate file is at the following path:

```
ios/Runner/AppDelegate.swift
```

2. Import `notifly_sdk`.

```swift theme={null}
import notifly_sdk
```

3. Update `AppDelegate.swift`.

Override the relevant `FlutterAppDelegate` methods to add the Notifly integration code.

| Method | Description |
| - | - |
| `application(_:didFinishLaunchingWithOptions:)` | Set the `UNUserNotificationCenter` delegate to `self`. |
| `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` | Register the APNs token with Notifly. |
| `application(_:didFailToRegisterForRemoteNotificationsWithError:)` | Notify Notifly if APNs registration fails. |
| `userNotificationCenter(_:didReceive:withCompletionHandler:)` | Forward push notification click events. |
| `userNotificationCenter(_:willPresent:withCompletionHandler:)` | Handle push notification display while the app is in the foreground. |

> [tab] Swift
>
> ```swift title="AppDelegate.swift" highlight={13, 21-23, 30-32, 39-41, 48-51} theme={null}
> import Flutter
> import notifly_sdk
> import UIKit
>
> @UIApplicationMain
> @objc class AppDelegate: FlutterAppDelegate {
>
>     override func application(
>         _ application: UIApplication,
>         didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
>     ) -> Bool {
>         GeneratedPluginRegistrant.register(with: self)
>         UNUserNotificationCenter.current().delegate = self
>         return super.application(application, didFinishLaunchingWithOptions: launchOptions)
>     }
>
>     override func application(
>         _ application: UIApplication,
>         didFailToRegisterForRemoteNotificationsWithError error: Error
>     ) {
>         Notifly.application(application,
>                             didFailToRegisterForRemoteNotificationsWithError: error)
>         super.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
>     }
>
>     override func application(
>         _ application: UIApplication,
>         didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
>     ) {
>         Notifly.application(application,
>                             didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
>         super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
>     }
>
>     override func userNotificationCenter(_ notificationCenter: UNUserNotificationCenter,
>                                         didReceive response: UNNotificationResponse,
>                                         withCompletionHandler completion: @escaping () -> Void)
>     {
>         Notifly.userNotificationCenter(notificationCenter,
>                                     didReceive: response)
>         super.userNotificationCenter(notificationCenter, didReceive: response, withCompletionHandler: completion)
>     }
>
>     override func userNotificationCenter(_ notificationCenter: UNUserNotificationCenter,
>                                         willPresent notification: UNNotification,
>                                         withCompletionHandler completion: @escaping (UNNotificationPresentationOptions) -> Void)
>     {
>         Notifly.userNotificationCenter(notificationCenter,
>                                     willPresent: notification,
>                                     withCompletionHandler: completion)
>         super.userNotificationCenter(notificationCenter, willPresent: notification, withCompletionHandler: completion)
>     }
> }
> ```

### Configure an iOS Notification Service Extension (recommended)

> [!NOTE]
>
> Requires `notifly-sdk` version 1.3.0 or later.

Configure a Notification Service Extension to use rich push notifications. Follow the [Push Extension guide](https://docs.notifly.tech/en/advanced/rich-push-notification.md).

#### Supported features

1. Attach images and videos to push notifications.
2. Track push notification delivery to analyze campaign performance in more detail.

> [!WARNING]
>
> The SDK works without a Notification Service Extension, but rich push notifications and delivery tracking are unavailable.

### Initialize the SDK

Add the Notifly plugin initialization code to your app's entry point, such as `main.dart`.

You can load environment variables with a package such as `dotenv`.

```dart title="main.dart" theme={null}
import 'package:notifly_flutter/notifly_flutter.dart';

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await NotiflyPlugin.initialize(
        projectId: dotenv.env['NOTIFLY_PROJECT_ID']!,
        username: dotenv.env['NOTIFLY_USERNAME']!,
        // `password` is a legacy compatibility placeholder. Do not pass a real password or API Secret Key.
        password: dotenv.env['NOTIFLY_USERNAME']!,
    );
}
```

> [!NOTE]
>
> Find `NOTIFLY_PROJECT_ID` and `NOTIFLY_USERNAME` on the settings page. `password` is a placeholder for backward compatibility. Pass the same nonempty value as `username`. Do not pass a real password or API Secret Key.

## 2. Register user information

Notifly uses user identifiers (`userId`) and user properties (`params`) to personalize marketing campaigns.\
Registered user information supports segmentation and targeting for channels such as push notifications, email, and Kakao AlimTalk.

### 1. Set the user ID (`NotiflyPlugin.setUserId()`)

Map `userId` to the identifier of the signed-in user in your app.\
Notifly uses this value to track user events and personalize campaigns.

### Parameters

**userId** `String`

The signed-in user's ID. Pass `null` on sign-out to clear the association.

```dart theme={null}
NotiflyPlugin.setUserId(userId);
```

#### Clear the user ID

On sign-out, call `setUserId(null)` to clear the association between the current device and the user.
To retain the same user data, manage it separately on your server or in your app.

> [tab] Dart
>
> ```dart title="setUserId" highlight={5, 17} theme={null}
> ElevatedButton(
>     onPressed: () async {
>         try {
>             final userIdInput = _userIdTextInputController.text;
>             await NotiflyPlugin.setUserId(userIdInput); // Set the user ID.
>         } catch (error) {
>             ...
>         }
>     },
>     child: const Text('Set User Id'),
>     ...
> ),
> ElevatedButton(
>     onPressed: () async {
>         try {
>             final userIdInput = _userIdTextInputController.text;
>             await NotiflyPlugin.setUserId(null); // Clear the user ID.
>         } catch (error) {
>             ...
>         }
>     },
>     child: const Text('Unregister User Id'),
>     ...
> ),
> ```

### 2. Set user properties

`setUserProperties` registers properties for the user.\
These properties support **segment targeting**, **message personalization**, and **delivery channel selection**.

> [!NOTE]
>
> **Before you send sensitive user properties**
>
> Before you send a custom user property that needs protection, such as a name or address, register it with the exact key you plan to send and enable encryption under **User Management > User List > Property management** in the console.
>
> See [Manage user properties](https://docs.notifly.tech/en/user-guide/users/properties.md) for setup instructions and limitations.

```dart theme={null}
NotiflyPlugin.setUserProperties(params);
```

**params** `Map\<String, Object\>` *required*

Key-value pairs of user properties. Supports predefined keys such as `$email`, `$phone_number`, and `$line_user_id`.

> [!NOTE]
>
> * `$email`: Email address for email campaigns.
> * `$phone_number`: Phone number for SMS and Kakao campaigns.
> * `$line_user_id`: LINE user ID for LINE message campaigns.
> * Custom fields: Define your own fields, such as `"plan"`, `"tier"`, and `"country"`.

> [tab] Dart
>
> ```dart title="setUserProperties" highlight={5} theme={null}
> ElevatedButton(
>     onPressed: () async {
>         try {
>             final value = _userPropertiesValueInputController.text;
>             await NotiflyPlugin.setUserProperties({'name': value});
>         } catch (error) {
>             ...
>         }
>     },
>     ...
> ),
> ```

## 3. Log events

Record user behavior to use in **campaign triggers**, **segment conditions**, and **performance analysis**.\
For example, collect button clicks, page visits, and completed purchases as events.

```dart theme={null}
NotiflyPlugin.trackEvent(
    eventName: eventName,
    eventParams: eventParams,
    segmentationEventParamKeys: segmentationEventParamKeys,
);
```

### Parameters

**eventName** `String` *required*

Event name, such as `"click_button"` or `"purchase_completed"`.

**eventParams** `Map\<String, Object\>`

Additional event parameters, such as `"plan": "premium"` or `"duration": 120`.

**segmentationEventParamKeys** `List\<String\>`

List of event parameter keys to use for segmentation. Supports at most one key.

> [!NOTE]
>
> Use `segmentationEventParamKeys` to make an event parameter (`eventParams`) available for targeting. You can specify **at most one key**.

> [tab] Dart
>
> ```dart title="trackEvent" theme={null}
> ...
> await NotiflyPlugin.trackEvent(
>     eventName: 'click_button_1',
>     eventParams: {'show_id': show_id},
> );
> ...
> ```

***

## 4. Get the internal user ID

`getNotiflyUserId()` returns the unique user ID that Notifly manages internally.\
This ID is **separate from the user ID set with `setUserId()`**. Most integrations do not need it.\
Use it when an external CRM or third-party integration requires Notifly's internal user ID.

> [!WARNING]
>
> This method is not supported on the web.

```dart theme={null}
NotiflyPlugin.getNotiflyUserId();
```

***

## 5. Configure web push notifications (web only)

Complete this section **only if you use web push notifications in Flutter Web**.\
For iOS and Android apps, skip this section.

***

### 1. Register the service worker

Register a **service worker** to receive web push notifications.

1. Create `notifly-service-worker.js` in your Flutter project's `web/` directory.
2. Add the following code:

```js title="web/notifly-service-worker.js" theme={null}
self.importScripts(
  "https://cdn.jsdelivr.net/npm/notifly-js-sdk@2/dist/NotiflyServiceWorker.js"
);
```

> [!NOTE]
>
> This file receives and displays push notifications while the browser runs in the background.

### 2. Request web push permission

Web push notifications require the user's explicit permission in the browser.

1. Automatic permission request (default)

* In the Notifly console, go to **Settings > SDK Settings > Website Settings**. Under **Permission Prompt Settings**, turn on **Auto Display**.

* When enabled, the permission prompt appears automatically when a user visits your website.

2. Manual permission request (optional)

![Web push permission settings](https://mintcdn.com/notifly/0_mniRtlC78csfem/images/i18n/en/developer-guide/web-push/flutter-web-push-permission.png?fit=max\&auto=format\&n=0_mniRtlC78csfem\&q=85\&s=f8075d3d73e71d31bd4f8e4f885cc14b)

* Turn off the automatic display option in the console to control when your app requests permission.

* Call the following method:

```dart theme={null}
import 'package:notifly_flutter/notifly_flutter.dart';

await NotiflyPlugin.requestPermission();
```

> [!NOTE]
>
> `requestPermission()` works **only when automatic permission requests are turned off** in the console.

### 3. Permission behavior

1. If the user has not chosen a permission setting, the prompt appears.

![Browser notification permission prompt](https://mintcdn.com/notifly/umP8GQfcNYrXNUqj/ko/developer-guide/image/javascript-sdk/web-push/web_push_permission_prompt.png?fit=max\&auto=format\&n=umP8GQfcNYrXNUqj\&q=85\&s=7ba9e9270cbcaa5d1133420ec1310048)

2. If the user has already granted permission, the prompt does not appear again.

3. If the user has denied permission, browser policy prevents the prompt from appearing again.

***

## 6. Test the integration

After you install the SDK, follow [Test your integration](https://docs.notifly.tech/en/integration-test.md) to verify event collection and push notification delivery.

***

## 7. Advanced integration

> [card] [Push notification icons](https://docs.notifly.tech/en/advanced/push-notification-icon.md)

> [card] [Request push notification permission](https://docs.notifly.tech/en/advanced/push-notification-consent.md)

> [card] [Push notification click events](https://docs.notifly.tech/en/advanced/push-notification-click-events.md)

## FAQ

> [accordion] Can I use Notifly with an existing Firebase Cloud Messaging integration?
>
> The Notifly Android SDK can work alongside Firebase Cloud Messaging that your app already uses.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.