# Flutter のネイティブ広告インテグレーション

> LevelPlay SDK を使用してネイティブ広告を Flutter アプリケーションに統合し、広告のカスタマイズ用に事前定義されたテンプレートとカスタムテンプレートの両方を提供します。

ネイティブ広告は、アプリケーション内の他のコンテンツに溶け込むようにカスタマイズできる広告の形式です。これにより、広告がよりオーガニックに表示され、ユーザー エクスペリエンスとリテンションの向上につながります。

## 前提条件##prerequisites

LevelPlay Flutter プラグイン 8.4.0 以降がアプリケーションに正しく[統合され](/grow/levelplay/sdk/flutter/plugin-integration.md)ていることを確認します。

## LevelPlay ネイティブ広告の統合##integrate-levelplay-native-ads

Flutter プラグインを使用して LevelPlay ネイティブ広告を統合する方法は 2 つあります。

* ネイティブ:XML および XIB ファイルの形式でプラグインによって提供される定義済みテンプレート
* カスタムテンプレート:開発者によってスタイル設定および設計されたテンプレート

## ネイティブ##native-templates

ネイティブは、ネイティブ広告ロジックを実装する定義済みビューです。この設定は、広告がロードされた後にビューの数を処理し、広告が破棄された後にビューをクリアします。

2 つのテンプレートオプションがあります。

* 小:メディアビューを含まないテンプレート。
* 中:メディアビューを特徴とするテンプレート。

スタイリングは一般的に似ていますが、好みに応じてカスタマイズすることもできます。

ネイティブを統合するには、以下の手順を実行します。

### Create LevelPlayNativeAd Object##create-levelplaynativead-object

`LevelPlayNativeAdView`コンテナに広告をロードする`LevelPlayNativeAd`オブジェクトを作成します。このオブジェクトはロード、破棄などの広告メソッドをハンドルし、広告の配置とイベントコールバックのリスナーを定義します。

```dart
_nativeAd = LevelPlayNativeAd.builder()
        .withPlacementName([YOUR_PLACEMENT])
        .withListener([YOUR_LEVEL_PLAY_NATIVE_AD_LISTENER])
        .build();

```

### リスナーの実装##implement-the-listener

コードに`LevelPlayNativeAdListener`を実装します。LevelPlay SDK は、ネイティブ広告アクティビティを通知するためにいくつかのコールバックを起動します。SDKはリスナーに以下のすべてのイベントを通知します。

```dart
/**
 ネイティブ広告がクリックされた後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */ 
@override
void onAdClicked(LevelPlayNativeAd? nativeAd, IronSourceAdInfo? adInfo) {}
/**
 ネイティブアドインプレッションが記録された後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */
 @override
 void onAdImpression(LevelPlayNativeAd? nativeAd, IronSourceAdInfo? adInfo) {}
/**
 ネイティブが広告のロードを試行したが失敗した後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param error エラーの理由
 */  
@override
void onAdLoadFailed(LevelPlayNativeAd? nativeAd, IronSourceError? error) {}
/**
 ネイティブ広告が正常にロードされた後に呼び出されます。
 @param nativeAd Level ネイティブ広告の再生。
 @param adInfo 広告の情報。
 */
@override
void onAdLoaded(LevelPlayNativeAd? nativeAd, IronSourceAdInfo? adInfo) {}

```

### Create LevelPlayNativeAdView##create-levelplaynativeadview

`LevelPlayNativeAdView`ウィジェットを作成して、ロードされたネイティブ広告をホストするコンテナを定義します。このオブジェクトは、幅と高ささを決定するか、コンテナのボックス制約を設定することで、ネイティブの広告境界を定義します。また、タイトル、ボディ、広告主、アクション呼び出しボタンなどのネイティブ広告要素のスタイル設定もハンドルできます。

ネイティブ テンプレートのデフォルト タイプは `SMALL` です。ウィジェット作成でテンプレート タイプを定義することで変更できます。 

```dart
LevelPlayNativeAdView(
          高さ:350, // Medium タイプに推奨される高ささ
          width:300， // 中サイズのタイプに推奨される幅
          nativeAd: _nativeAd,
          onPlatformViewCreated: () {
            _nativeAd?.loadAd(); // Recommeneded place to loadAd
          },
          templateType:LevelPlayTemplateType.MEDIUM,
          templateStyle: [LevelPlayNativeAdTemplateStyle] 任意
)
LevelPlayNativeAdView(
          高さ:175, // Small Type に推奨される高ささ
          width:300， // Small Type に推奨される幅
          nativeAd: _nativeAd,
          onPlatformViewCreated: () {
            _nativeAd?.loadAd(); // Recommeneded place to loadAd
          },
          templateType:LevelPlayTemplateType.SMALL,
          templateStyle: [LevelPlayNativeAdTemplateStyle] 任意
)

```

### 広告のロード##load-the-ad

loadAd を呼び出してネイティブ広告をロードします。ネイティブ広告ビューコンテナの`onPlatformViewCreated`コールバックを受信した後、または開発者が決めた別のタイミングで呼び出すことができます。

```dart
_nativeAd?.loadAd();

```

### ネイティブ広告の破棄##destroy-the-native-ad

ネイティブ広告を破棄するには、以下のメソッドを呼び出します。

```dart
  _nativeAd?.destroyAd();

```

破棄されたネイティブ広告はロードできません。再度配信する場合は、広告ウィジェットする必要があります。

## カスタムテンプレート##custom-templates

カスタムテンプレートを使用すると、特定のニーズに合わせて独自のスタイルと機能を設計できます。レイアウトと機能を柔軟にカスタマイズできるため、一意のユーザー体験が保証されます。

これらのテンプレートは、主に広告デザインをより高いレベルでコントロールする必要がある場合に使用されます。Android と iOS の両方のプラットフォームに実装でき、追加コード実装が必要です。

カスタムテンプレートを作成するには、ネイティブコードを記述し、独自のカスタムレイアウトを開発する必要があります。インテグレーションのステップは以下の通りです。

### Create NativeAdViewFactory##create-nativeadviewfactory

LevelPlayNativeAdViewFactory を拡張するクラスの Android または iOS の実装では、カスタマイズされたレイアウトを使用してロードされた広告がディスプレイされます。

#### Android##android

```kotlin
// Android Implementation 
import com.ironSource.ironsource_mediation.LevelPlayNativeAdViewFactory
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import com.ironsource.mediationsdk.ads.nativead.LevelPlayMediaView
import com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAd
import com.ironsource.mediationsdk.ads.nativead.NativeAdLayout
import io.flutter.plugin.common.BinaryMessenger
/**
 * このクラスは、カスタムネイティブ広告の実装方法の例です。
 * クラスは BinaryMessenger と
 * 開発者がロードするネイティブ広告レイアウト。それはまた
 * LevelPlayNativeAdViewFactory を拡張し、
 * ビューを
 * ロードされたネイティブ広告。
 */
class NativeAdViewFactoryExample(
    levelPlayBinaryMessenger:BinaryMessenger,
    layoutId:Int
) :LevelPlayNativeAdViewFactory(levelPlayBinaryMessenger, layoutId) {
    override fun bindNativeAdToView(nativeAd:LevelPlayNativeAd?, nativeAdLayout:NativeAdLayout) {
        // Extract views
        val titleView = nativeAdLayout.findViewById<TextView>(R.id.adTitle)
        val bodyView = nativeAdLayout.findViewById<TextView>(R.id.adBody)
        val advertiserView = nativeAdLayout.findViewById<TextView>(R.id.adAdvertiser)
        val callToActionView = nativeAdLayout.findViewById<Button>(R.id.adCallToAction)
        val iconView = nativeAdLayout.findViewById<ImageView>(R.id.adAppIcon)
        val mediaView = nativeAdLayout.findViewById<LevelPlayMediaView>(R.id.adMedia)
        // Bind native ad to view
        if (nativeAd != null) {
            if (nativeAd.title != null) {
                titleView.text = nativeAd.title
                nativeAdLayout.setTitleView(titleView)
            }
            if (nativeAd.body != null) {
                bodyView.text = nativeAd.body
                nativeAdLayout.setBodyView(bodyView)
            }
            if (nativeAd.advertiser != null) {
                advertiserView.text = nativeAd.advertiser
                nativeAdLayout.setAdvertiserView(advertiserView)
            }
            if (nativeAd.callToAction != null) {
                callToActionView.text = nativeAd.callToAction
                nativeAdLayout.setCallToActionView(callToActionView)
            }
            if (nativeAd.icon != null) {
                iconView!!.setImageDrawable(nativeAd.icon!!.drawable)
                nativeAdLayout.setIconView(iconView)
            }
            if (mediaView != null) {
                nativeAdLayout.setMediaView(mediaView)
            }
            nativeAdLayout.registerNativeAdViews(nativeAd)
        }
    }
}

```

#### iOS##ios

```objc
// iOS Implementation
/// h file
#import <Foundation/Foundation.h>
#import <Flutter/Flutter.h>
#import <IronSource/IronSource.h>
#import "LevelPlayNativeAdViewFactory.h"
/**
 * このクラスは、カスタムネイティブ広告の実装方法の例です。
 * クラスは BinaryMessenger と
 * 開発者がロードするネイティブ広告レイアウト。それはまた
 * LevelPlayNativeAdViewFactory を拡張し、
 * ビューを
 * ロードされたネイティブ広告。
 */
@interface NativeAdViewFactoryExample :LevelPlayNativeAdViewFactory <LevelPlayNativeAdViewFactoryDelegate>
- (instancetype)initWithMessenger:(id<FlutterBinaryMessenger>)levelPlayBinaryMessenger layoutName:(nullable NSString *)layoutName;
@end
/// m file
#import "NativeAdViewFactoryExample.h"
@implementation NativeAdViewFactoryExample
- (instancetype)initWithMessenger:(id<FlutterBinaryMessenger>)levelPlayBinaryMessenger layoutName:(nullable NSString *)layoutName {
    self = [super initWithMessenger:levelPlayBinaryMessenger delegate:self layoutName:layoutName];
    return self;
}
- (void)bindNativeAdToView:(LevelPlayNativeAd *)nativeAd isNativeAdView:(ISNativeAdView *)isNativeAdView {
    // Extract views
    UILabel *titleView = isNativeAdView.adTitleView;
    UILabel *bodyView = isNativeAdView.adBodyView;
    UILabel *advertiserView = isNativeAdView.adBodyView;
    UIButton *callToActionView = isNativeAdView.adCallToActionView;
    UIImageView *iconView = isNativeAdView.adAppIcon;
    LevelPlayMediaView *mediaView = isNativeAdView.adMediaView;
    // Bind native ad to view
    if (nativeAd != nil) {
        if (nativeAd.title != nil) {
            titleView.text = nativeAd.title;
            [isNativeAdView setAdTitleView:titleView];
        }
        if (nativeAd.body != nil) {
            bodyView.text = nativeAd.body;
            [isNativeAdView setAdBodyView:bodyView];
        }
        if (nativeAd.advertiser != nil) {
            advertiserView.text = nativeAd.advertiser;
            [isNativeAdView setAdAdvertiserView:advertiserView];
        }
        if (nativeAd.callToAction != nil) {
            [callToActionView setTitle:nativeAd.callToAction forState:UIControlStateNormal];
            [isNativeAdView setAdCallToActionView:callToActionView];
        }
        if (nativeAd.icon != nil) {
            iconView.image = nativeAd.icon.image;
            [isNativeAdView setAdAppIcon:iconView];
        }
        if (mediaView != nil) {
            [isNativeAdView setAdMediaView:mediaView];
        }
        // Register native ad views with the provided native ad
        [isNativeAdView registerNativeAdViews:nativeAd];
    }
}
@end

```

### NativeAdViewFactory の登録##register-your-nativeadviewfactory

クラスを MainActivity または AppDelegate に登録します。

> **Note:**
>
> 一意ののビューの文字文字列は、Flutter 側の LevelPlayNativeAdウィジェットで設定した viewType に対応している必要があります。

#### Android##android

```kotlin
 // Android Implementation 
import com.ironSource.ironsource_mediation.IronSourceMediationPlugin
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
クラス MainActivity：FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine:FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        // Custom native ad view template must be registered here
        IronSourceMediationPlugin.registerNativeAdViewFactory(flutterEngine, [YOUR_一意のビュー_TYPE], NativeAdViewFactoryExample(flutterEngine.dartExecutor.binaryMessenger, R.Layout.my_custom_ネイティブ_ad_ビュー)) //xml id
    }
    override fun cleanUpFlutterEngine(flutterEngine:FlutterEngine) {
        super.cleanUpFlutterEngine(flutterEngine)
        // Custom native ad view template must be unregistered here
        IronSourceMediationPlugin.unregisterNativeAdViewFactory(flutterEngine, viewType)
    }
}

```

Android NativeAdView レイアウトの例については、 [my＿custom＿ネイティブ＿ad＿ビュー＿テンプレート.xml](https://github.com/ironsource-mobile/Flutter-SDK/blob/master/example/android/app/src/main/res/layout/my_custom_native_ad_view.xml) を参照してください。

#### iOS##ios

```objc
 // iOS Implementation 
#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "NativeAdViewFactoryExample.h"
#import "IronSourceMediationPlugin.h"
@implementation AppDelegate
- (ブーリアン)アプリケーション:(UIApplication *)アプリケーション
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  UIViewController *rootViewController = self.window.rootViewController;
  // Check if the root view controller is a FlutterViewController
  if ([rootViewController isKindOfClass:[FlutterViewController class]]) {
    // Cast the root view controller to FlutterViewController
    FlutterViewController *flutterViewController = (FlutterViewController *)rootViewController;
    NativeAdViewFactoryExample *nativeAdViewFactoryExample = [[NativeAdViewFactoryExample alloc] initWithMessenger: flutterViewController.binaryMessenger layoutName: @"MyCustomNativeAdViewTemplate"]; // xib 名
    // Custom native ad view template must be registered here
    [IronSourceMediationPlugin registerNativeAdViewFactory:self
                                                  viewTypeId:[YOUR_UNIQUE_VIEW_TYPE]
                                         nativeAdViewFactory:nativeAdViewFactoryExample];
  }
  // Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

```

iOS NativeAdView レイアウトの例については、[MyCustomNativeAdViewTemplate.xib](https://github.com/ironsource-mobile/Flutter-SDK/blob/master/example/ios/Runner/MyCustomNativeAdViewTemplate.xib) を参照してください。

### Create LevelPlayNativeAdView##create-levelplaynativeadview

LevelPlayNativeAdウィジェットを作成して、ロードされたネイティブ広告をホストするコンテナを定義します。このオブジェクトは、幅と高ささを決定するか、コンテナのボックス制約を設定することで、ネイティブの広告境界を定義します。また、タイトル、ボディ、広告主、アクション呼び出しボタンなどのネイティブ広告要素のスタイル設定もハンドルできます。

> **Note:**
>
> カスタムテンプレートを作成する場合は、viewType がネイティブの Android または iOS セクションで指定されている一意ののビューと一致することを確認してください。

```dart
LevelPlayNativeAdView(
          高さ: [高さ], // 推奨の高ささ
          幅:[幅], // 推奨される幅
          nativeAd: _nativeAd,
          onPlatformViewCreated: () {
            _nativeAd?.loadAd(); // Recommeneded place to loadAd
          },
          viewType: [YOUR_UNIQUE_VIEW_TYPE]
)

```

### 広告のロード##load-the-ad

loadAd を呼び出してネイティブ広告をロードします。このメソッドは、ネイティブ広告ビューコンテナの onPlatformViewCreated コールバック、または開発者が決めた別のタイミングで呼び出すことができます。

```dart
_nativeAd?.loadAd();

```

### ネイティブ広告の破棄##destroy-the-native-ad

ネイティブ広告を破棄するには、 destroyAd メソッドを実行します。

```dart
_nativeAd?.destroyAd();

```

破棄されたネイティブ広告はロードできません。再度配信する場合は、広告ウィジェットする必要があります。

## LevelPlay Mediation デモアプリケーション##levelplay-mediation-demo-app

インテグレーション Demo (インテグレーションデモ) アプリケーションでは、ネイティブの広告単位 API をアプリケーションに統合する方法を示します。

[Flutter デモアプリケーションをダウンロード](https://github.com/ironsource-mobile/Flutter-SDK/tree/master/example)

[インテグレーションテストスイート](/grow/levelplay/sdk/flutter/integration-test-suite/.md)とのインテグレーションを確認します。

## 次のステップ##next-steps

インテグレーションガイドに従って、追加のインタースティシャル広告ネットワークを統合したり、追加の広告フォーマットを設定したりできます。

* [メディエーションネットワークの追加](/grow/levelplay/sdk/flutter/mediation-networks.md)
* [リワード広告](/grow/levelplay/sdk/flutter/rewarded-ads-integration.md)
* [インタースティシャル広告](/grow/levelplay/sdk/flutter/interstitial-integration.md)
* [バナー広告](/grow/levelplay/sdk/flutter/banner-integration.md)
