> For the complete documentation index, see [llms.txt](https://documentation.pushly.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://documentation.pushly.com/pushly-ja/integration/implementation-steps/flutter/sdk-flutter.md).

# SDK: Flutter

{% hint style="info" %}
Native App Push の統合は現在クローズドベータ版です。ベータパートナーになる方法の詳細については、アカウントマネージャーにお問い合わせください。
{% endhint %}

## ステップ 1: PushSDK プラグインをインポートする

PushSDK プラグインをインストールする

{% tabs %}
{% tab title="Flutter" %}

```sh
flutter pub add pushly_pushsdk
```

{% endtab %}
{% endtabs %}

## ステップ2: Androidのセットアップ

### ステップ2.1: Gradle

必要な依存関係を追加して、gradleスクリプトを更新します:

{% tabs %}
{% tab title="android/build.gradle" %}

```gradle
buildscript {
    ...
    dependencies {
        ...
        classpath 'com.google.gms:google-services:4.3.13'
    }
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="android/app/build.gradle" %}

```gradle
android {
    compileSdk 33
    ...

    defaultConfig {
        ...
        targetSdk 33
    }
}

apply plugin: 'com.google.gms.google-services'
```

{% endtab %}
{% endtabs %}

### ステップ2.2: Google Services

次のファイルを追加します `google-services.json` ファイルを `android/app` ディレクトリに。

## ステップ3: iOSのセットアップ

### ステップ3.1: Podsをインストールする

次の場所で `<project_root>/ios` ディレクトリ内で以下を実行します: `pod install`

### ステップ3.2: Notification Service Extensionを追加する

画像やカスタムアクションをサポートするリッチ通知を有効にするには、Notification Service Extensionが必要です。

アプリの **xcworkspace** を使ってXCodeを開きます。次に、 `File > New > Target` を選択し、続いて `Notification Service Extension` をiOSテンプレートタブ内で選択して、 `Next`.

<figure><img src="/files/0d74fa664d091c410531eb9ecff49e7516019f10" alt=""><figcaption></figcaption></figure>

"NotificationServiceExtension"を `Product Name` に入力し、アプリ拡張の他の設定詳細も入力してから、 `Finish` をクリックしますが、 **その後のダイアログでは有効化をクリックしないでください** 。

<figure><img src="/files/70da4bb154a18f120bda98b62a63ce8991f81e66" alt=""><figcaption></figcaption></figure>

クリック `キャンセル` モーダルが閉じた後にデプロイメントターゲットを設定できるように、サービス拡張の有効化を求めるダイアログで

<img src="/files/f6e3d871b45ca43a08967ec042dd669ed723c05a" alt="" data-size="original">

デプロイメントターゲットを **メインのアプリケーションターゲットと同じ**に設定してください。特別な理由がない限り、 `Deployment Target` をiOS 11に設定するべきです。これはPushSDK Frameworkおよび最新のXCodeでサポートされるiOSの最低バージョンです。

### ステップ3.3: サービス拡張にPushly依存関係を追加する

次のファイルで `<project_root>/ios/Podfile`、 **NotificationServiceExtension** あなたの〜と同じ階層に **Runner** ターゲット:

{% tabs %}
{% tab title="Podfile" %}

```ruby
target 'NotificationServiceExtension' do
  use_frameworks!
  pod 'Pushly', '>= 1.0', '< 2.0'
end
```

{% endtab %}

{% tab title="Podfileの例" %}

```ruby
# グローバルなプラットフォームをプロジェクトに定義するには、この行のコメントを外してください
platform :ios, '11.0'

# CocoaPods の分析機能はネットワーク統計を同期的に送信し、flutter のビルド遅延に影響します。
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

target 'NotificationServiceExtension' do
  use_frameworks!
  pod 'Pushly', '>= 1.0', '< 2.0'
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end
```

{% endtab %}
{% endtabs %}

Podfileにサービス拡張の依存関係を追加したので、再度インストールを実行する必要があります。 `<project_root>/ios` ディレクトリ内で、以下を実行します: `pod install`.

### ステップ3.4: サービス拡張を更新する

次に、新しく作成されたNotification Service Extensionを開き、コードを以下の内容に置き換えます:

{% tabs %}
{% tab title="Swift" %}

```swift
import Pushly

class NotificationService: PNNotificationServiceExtension {
}
```

{% endtab %}

{% tab title="Objective-C" %}

```objectivec
// ヘッダーファイルのインポートは保持してください
#import "NotificationService.h"

@import Pushly;

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    [PNNotificationServiceExtensionHandler didReceiveExtensionRequest:request content:self.bestAttemptContent withContentHandler:contentHandler];
}

- (void)serviceExtensionTimeWillExpire {
    // 拡張機能がシステムによって終了される直前に呼び出されます。
    // 変更された内容の「最善の試行」を配信する機会として使用してください。そうしないと、元のプッシュペイロードが使用されます。
    [PNNotificationServiceExtensionHandler didRecieveExtensionTimeWillExpire:self.bestAttemptContent withContentHandler:self.contentHandler];

    self.contentHandler(self.bestAttemptContent);
}

@end
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Xcode が Pushly を見つけられないと警告する場合は、物理デバイス、またはビルド先として「Any iOS Device」が選択されていることを確認してください。
{% endhint %}

### ステップ3.4: メインアプリケーションターゲットに機能を追加する

{% hint style="warning" %}
Push Notifications機能は、 **メインのアプリケーションターゲット**.
{% endhint %}

のみに追加する必要があります。ルートプロジェクトを選択し、その後にメインのアプリケーションターゲット > `Signing & Capabilities`

<figure><img src="/files/50bb70546375b351b4daec1b886c44738f1f9f3a" alt=""><figcaption></figcaption></figure>

次をクリックします `+ Capability` を選択して、 `Push Notifications`.

次をクリックします `+ Capability` を選択して、 `Background Modes`.

を追加します。 `Background Modes` 機能を追加した後、 `Remote Notifications` が有効になっていることを確認してください。

<figure><img src="/files/ddaf430796151ed89742326cba0b37531feb5624" alt=""><figcaption></figcaption></figure>

次をクリックします `+ Capability` を選択して、 `App Groups`.

次をクリックします `+` 内にある `App Groups` セクションのシンボルを使って新しい名前付きコンテナーを追加します。PushSDKが情報を正しく取得できるようにするには、コンテナー名を `group.{app-bundle-id}.push`.

<figure><img src="/files/26812bff850bd6638d723523857e2a406d744acc" alt=""><figcaption></figcaption></figure>

にする必要があります。メインのアプリケーションターゲットで、新しく作成したApp Groupの横のチェックボックスをオンにします。

### ステップ3.5: Notification Service Extensionに機能を追加する

次に、 **NotificationServiceExtension** ターゲットで `Signing & Capabilities` タブの下に表示されます。

次をクリックします `+ Capability` を選択して、 `App Groups`.

最後に、新しく作成したApp Groupの横のチェックボックスをオンにします。

## ステップ4: SDKの初期化

次のファイルで `main.dart` ファイルで、以下のサンプル実装コードを使ってPushSDKを初期化します。

次の `REPLACE_WITH_SDK_KEY` を `setConfiguration` メソッド内で、プラットフォーム設定ページのSDKキーに置き換えてください。

{% tabs %}
{% tab title="main.dart" %}

```dart
...
import 'package:pushly_pushsdk/pushsdk.dart';

...
// アプリの初期化関数内で
await PushSDK.setLogLevel(PNLogLevel.info);
await PushSDK.setConfiguration('REPLACE_WITH_SDK_KEY');

await PushSDK.showNativeNotificationPermissionPrompt(completion: ( granted, status, error ) {
    print('権限が付与されました: $granted');
});
```

{% endtab %}
{% endtabs %}

Androidデバイスまたはエミュレーター（エミュレーターに `Google Play ストア サービス` がインストールされていることを確認してください）、またはiOS向けにビルドする場合はiOSデバイスでアプリを実行し、正しくビルドされることを確認してください。

前のステップで追加したコードにより、アプリ起動時にプッシュ権限ダイアログが表示されます。これは [<mark style="color:青色;">SDK メソッド</mark>](/pushly-ja/integration/implementation-steps/flutter/sdk-flutter/sdkmesoddo.md) を使用して、ダイアログを表示するタイミングを制御することでカスタマイズできます。

ダイアログを承認した後、プラットフォームにログインして `Notifications > Create Notification` に移動し、適切な **ネイティブ: iOS** または **ネイティブ: Android** チャネル

## 次のステップ

SDK が正しく動作していることを確認したら、次のような追加のオプション機能を引き続き追加できます:

* [<mark style="color:青色;">通知の開封 / アプリリンク / ディープリンクの処理</mark>](/pushly-ja/integration/implementation-steps/flutter/sdk-flutter/dpurinku.md)
* [<mark style="color:青色;">購読者のプロフィールに属性を付与する</mark>](/pushly-ja/integration/implementation-steps/flutter/sdk-flutter/sdkmesoddo.md#adding-attributes-to-a-subscribers-profile)
* [<mark style="color:青色;">購読者がどのコンテンツとやり取りしたかに関する情報を送信する</mark>](https://documentation.pushly.com/pushly-ja/integration/implementation-steps/flutter/pages/b7dda43e94b09a32d55a3a04469afcc6c2a88543#userprofile.trackactivity)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://documentation.pushly.com/pushly-ja/integration/implementation-steps/flutter/sdk-flutter.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
