> ## 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

> Notifly Flutter SDKのインストール、iOSとAndroidの設定、プッシュ通知とアプリ内ポップアップの連携方法を説明します。

Notifly Flutterプラグインは、FlutterアプリにNotiflyを組み込むためのSDKです。

次の機能に対応しています。

* デバイス情報をNotiflyに登録し、プッシュ通知を受信したり、アプリ内ポップアップを表示したりできます。
  （アプリ内ポップアップは、アプリがフォアグラウンドのときにのみ表示されます。）
* イベントとユーザー情報をNotiflyに送信し、キャンペーンのターゲティングと分析に使用できます。
* ユーザー行動をイベントとして記録し、キャンペーンの効果を測定できます。

> [!NOTE]
>
> Androidのアプリ内ポップアップは、**Android 11（API 30）以降**でのみ利用できます。

## 事前準備

1. **Firebaseプロジェクトを連携します。**\
   Notifly iOS SDKは、プッシュ通知の送信に[Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging)を使用します。

> [Firebaseプロジェクトの連携ガイド](https://docs.notifly.tech/ja/developer-guide/firebase-integration.md)

2. **iOSのAPNs認証情報を登録します。**

> [APNs認証情報の登録](https://docs.notifly.tech/ja/developer-guide/firebase-integration.md#1-3-apns-認証キーを登録する)

> [!NOTE]
>
> * iOSを正しくビルドするには、Xcodeで`Runner.xcworkspace`を開いてください。

## 1. プラグインのセットアップ

### プラグインのインストール

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

`flutter pub add`コマンドは`pubspec.yaml`に依存関係を追加します。最新の公開バージョンはバッジで確認できます。[![Pub](https://img.shields.io/pub/v/notifly_flutter.svg)](https://pub.dev/packages/notifly_flutter)

### iOSの設定

#### 1. Capabilityの設定

1. Xcodeで`Runner.xcworkspace`を開きます。Notifly SDKを使用する場合は、`.xcodeproj`ではなくワークスペースを開いてください。

2. Xcodeでターゲットの最小デプロイバージョンをiOS 15.0以降に設定します。`Podfile`にも同じバージョンを指定します。

3. **Push Notifications**と**Background Modes**を有効にします。**Background Modes**では、**Remote notifications**と**Background fetch**を有効にしてください。

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

   ![Capabilityの追加](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. `AppDelegate.swift`の設定

1. ファイルの場所を確認します。

SwiftのAppDelegateファイルは、次の場所にあります。

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

2. `notifly_sdk`をインポートします。

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

3. `AppDelegate.swift`を編集します。

`FlutterAppDelegate`の該当するメソッドをオーバーライドして、Notiflyの連携コードを追加します。

| メソッド | 説明 |
| - | - |
| `application(_:didFinishLaunchingWithOptions:)` | `UNUserNotificationCenter`のdelegateを`self`に設定します。 |
| `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` | APNsトークンをNotiflyに登録します。 |
| `application(_:didFailToRegisterForRemoteNotificationsWithError:)` | APNsの登録に失敗したことをNotiflyに通知します。 |
| `userNotificationCenter(_:didReceive:withCompletionHandler:)` | プッシュ通知のクリックイベントを転送します。 |
| `userNotificationCenter(_:willPresent:withCompletionHandler:)` | フォアグラウンドでのプッシュ通知の表示を処理します。 |

> [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)
>     }
> }
> ```

### iOS Notification Service Extensionの設定（推奨）

> [!NOTE]
>
> `notifly-sdk`バージョン1.3.0以降で利用できます。

Notification Service Extensionを設定すると、リッチプッシュ通知を利用できます。[Push Extensionガイド](https://docs.notifly.tech/ja/advanced/rich-push-notification.md)に沿って設定してください。

#### 主な機能

1. プッシュ通知に画像や動画を添付できます。
2. プッシュ通知の受信状況を追跡し、キャンペーンの効果を詳しく分析できます。

> [!WARNING]
>
> Notification Service Extensionを設定しなくてもSDKは動作しますが、リッチプッシュ通知と受信トラッキングは利用できません。

### SDKの初期化

アプリのエントリーポイント（`main.dart`など）に、Notiflyプラグインの初期化コードを追加します。

環境変数の読み込みには、`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`は後方互換性のためのプレースホルダーです。実際のパスワードやAPI Secret Keyを指定しないでください。
        password: dotenv.env['NOTIFLY_USERNAME']!,
    );
}
```

> [!NOTE]
>
> `NOTIFLY_PROJECT_ID`と`NOTIFLY_USERNAME`は設定ページで確認できます。`password`は後方互換性のためのプレースホルダーです。`username`と同じ空でない値を渡してください。実際のパスワードやAPI Secret Keyは指定しないでください。

## 2. ユーザー情報の登録

Notiflyは、ユーザー識別子（`userId`）とユーザー属性（`params`）を使って、マーケティングキャンペーンをパーソナライズします。\
登録したユーザー情報は、セグメントの分類や、プッシュ通知、メール、カカオアリムトークなどの配信対象の設定に使用されます。

### 1. ユーザーIDの登録（`NotiflyPlugin.setUserId()`）

`userId`には、アプリ内でログインしているユーザーの識別子を設定します。\
Notiflyは、この値を使ってユーザーのイベントを追跡し、キャンペーンをパーソナライズします。

### パラメーター

**userId** `String`

ログインしているユーザーのIDです。ログアウト時に`null`を渡すと、関連付けが解除されます。

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

#### ユーザーIDの解除

ログアウト時には、`setUserId(null)`を呼び出して、現在のデバイスとユーザーの関連付けを解除することを推奨します。
同じユーザーデータを保持する必要がある場合は、サーバーまたはアプリ内で別途管理してください。

> [tab] Dart
>
> ```dart title="setUserId" highlight={5, 17} theme={null}
> ElevatedButton(
>     onPressed: () async {
>         try {
>             final userIdInput = _userIdTextInputController.text;
>             await NotiflyPlugin.setUserId(userIdInput); // ユーザーIDを登録します。
>         } catch (error) {
>             ...
>         }
>     },
>     child: const Text('Set User Id'),
>     ...
> ),
> ElevatedButton(
>     onPressed: () async {
>         try {
>             final userIdInput = _userIdTextInputController.text;
>             await NotiflyPlugin.setUserId(null); // ユーザーIDを解除します。
>         } catch (error) {
>             ...
>         }
>     },
>     child: const Text('Unregister User Id'),
>     ...
> ),
> ```

### 2. ユーザー属性の登録

`setUserProperties`で、ユーザーの属性情報を登録します。\
登録した情報は、**セグメントのターゲティング**、**メッセージのパーソナライズ**、**配信チャネルの選択**などに使用されます。

> [!NOTE]
>
> **機密性の高いユーザー属性を送信する前に**
>
> 氏名や住所など、保護が必要なカスタムユーザー属性を送信する前に、コンソールの**ユーザー管理** > **ユーザー一覧**の**属性管理**で、送信するキーと同じ名前の属性を登録し、暗号化を有効にしてください。
>
> 設定方法と利用上の制約については、[属性管理ガイド](https://docs.notifly.tech/ja/user-guide/users/properties.md)を確認してください。

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

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

ユーザー属性のキーと値のペアです。`$email`、`$phone_number`、`$line_user_id`などの定義済みキーを使用できます。

> [!NOTE]
>
> * `$email`: メールキャンペーンに使用するメールアドレスです。
> * `$phone_number`: SMSやカカオのキャンペーンに使用する電話番号です。
> * `$line_user_id`: LINEメッセージキャンペーンに使用するLINEユーザーIDです。
> * カスタムフィールド: `"plan"`、`"tier"`、`"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. イベントの記録

ユーザー行動を記録すると、**キャンペーンのトリガー**、**セグメントの条件**、**効果分析**などに使用できます。\
ボタンのクリック、ページへのアクセス、購入完了などのユーザー行動をイベントとして収集します。

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

### パラメーター

**eventName** `String` *required*

イベント名です。たとえば、`"click_button"`や`"purchase_completed"`を指定します。

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

イベントに付加するパラメーターです。たとえば、`"plan": "premium"`や`"duration": 120`を指定できます。

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

セグメントの分類に使用するイベントパラメーターキーのリストです。指定できるキーは最大1つです。

> [!NOTE]
>
> `segmentationEventParamKeys`を指定すると、イベントパラメーター（`eventParams`）を配信対象の設定などに使用できます。指定できるキーは**最大1つ**です。

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

***

## 4. 内部ユーザーIDの取得

`getNotiflyUserId()`は、Notiflyが内部で管理する一意のユーザーIDを返します。\
このIDは、`setUserId()`で登録するユーザーIDとは**別の識別子**です。通常の連携では使用する必要はありません。\
外部CRMやサードパーティーサービスとの連携で、Notiflyの内部ユーザーIDが必要な場合に使用します。

> [!WARNING]
>
> このメソッドはWeb環境では利用できません。

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

***

## 5. Webプッシュ通知の設定（Webのみ）

このセクションは、**Flutter WebでWebプッシュ通知を使用する場合のみ**実施してください。\
iOSとAndroidのモバイルアプリでは、このセクションをスキップできます。

***

### 1. Service Workerの登録

Webプッシュ通知を受信するには、**Service Worker**を登録する必要があります。

1. Flutterプロジェクトの`web/`フォルダーに、`notifly-service-worker.js`を作成します。
2. 次のコードを追加します。

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

> [!NOTE]
>
> このファイルは、ブラウザーのバックグラウンドでプッシュ通知を受信し、表示します。

### 2. Webプッシュ通知の許可リクエスト

Webプッシュ通知には、ブラウザー上でユーザーの明示的な許可が必要です。

1. 自動で許可をリクエストする場合（デフォルト）

* Notiflyコンソールで**設定 → SDK設定 → ウェブサイト設定**を開き、**権限要求ポップアップ設定**の**自動表示を使用**をオンにします。

* オンにすると、ユーザーがWebサイトにアクセスしたときに、通知の許可を求めるポップアップが自動で表示されます。

2. 手動で許可をリクエストする場合（任意）

![Webプッシュ通知の許可設定](https://mintcdn.com/notifly/DHduOkdsm1-HMvmh/images/i18n/ja/developer-guide/web-push/flutter-web-push-permission.png?fit=max\&auto=format\&n=DHduOkdsm1-HMvmh\&q=85\&s=be4b68a6de58174cad32f7a9f10f7b49)

* コンソールで**自動表示を使用**をオフにすると、通知の許可を求めるタイミングをアプリのコードで指定できます。

* 次のメソッドを呼び出します。

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

await NotiflyPlugin.requestPermission();
```

> [!NOTE]
>
> `requestPermission()`は、コンソールで**自動表示を使用**をオフにしている場合にのみ動作します。

### 3. 許可状態ごとの動作

1. ユーザーがまだ許可を設定していない場合は、ポップアップが表示されます。

![ブラウザーの通知許可リクエスト](https://mintcdn.com/notifly/DHduOkdsm1-HMvmh/images/i18n/ja/developer-guide/web-push/web-push-permission-prompt.png?fit=max\&auto=format\&n=DHduOkdsm1-HMvmh\&q=85\&s=1c612f0f5049cc5dcfd0078502df7734)

2. ユーザーがすでに許可している場合は、ポップアップは再表示されません。

3. ユーザーが拒否している場合は、ブラウザーのポリシーにより、ポップアップは再表示されません。

***

## 6. 連携テスト

SDKのインストール後、連携テストガイドに沿って、イベントの収集とプッシュ通知の受信を確認してください。\
[連携をテストする](https://docs.notifly.tech/ja/integration-test.md)

***

## 7. 高度な連携

> [card] [プッシュ通知アイコンの設定](https://docs.notifly.tech/ja/advanced/push-notification-icon.md)

> [card] [プッシュ通知の許可をリクエストする](https://docs.notifly.tech/ja/advanced/push-notification-consent.md)

> [card] [プッシュ通知のクリックイベント](https://docs.notifly.tech/ja/advanced/push-notification-click-events.md)

## FAQ

> [accordion] すでにFirebase Cloud Messagingを使用している場合はどうすればよいですか？
>
> Notifly Android SDKは、アプリで使用中のFirebase Cloud Messagingと併用できます。


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