Dart의 네이티브 템플릿

네이티브 템플릿은 네이티브 광고를 위한 코드 완성형 보기로, 빠른 구현과 손쉬운 수정을 위해 설계되었습니다. 네이티브 템플릿을 사용하면 플러그인에서 사전 빌드된 Android 및 iOS 레이아웃을 제공하며 개발자는 Dart API를 사용하여 네이티브 애셋의 스타일을 맞춤설정할 수 있습니다.

이 가이드에서는 Dart API를 사용하여 기본 플랫폼 뷰의 스타일을 지정하고 광고를 렌더링하는 방법을 보여줍니다.

기본 요건

  • Flutter 2.4.0 이상

항상 테스트 광고로 테스트

앱을 제작하고 테스트할 때는 운영 중인 실제 광고 대신 테스트 광고를 사용하세요. 테스트 광고를 로드하는 가장 쉬운 방법은 네이티브 광고 전용 테스트 광고 단위 ID를 사용하는 것입니다.

  • /6499/example/native

테스트 광고 단위는 모든 요청에 대해 테스트 광고를 반환하도록 구성되므로 코딩, 테스트, 디버깅 중에 앱에서 사용할 수 있습니다. 앱을 게시하기 전에 광고 단위 ID로 대체해야 합니다.

광고 로드

다음 예에서는 medium 크기의 네이티브 템플릿을 사용하여 네이티브 광고를 로드합니다.

class NativeExampleState extends State<NativeExample> {
  NativeAd? nativeAd;
  bool _nativeAdIsLoaded = false;

 // TODO: replace this test ad unit with your own ad unit.
 final _adUnitId = '/6499/example/native';

  /// Loads a native ad.
  void loadAd() {
    _nativeAd = NativeAd(
        adUnitId: _adUnitId,
        listener: NativeAdListener(
          onAdLoaded: (ad) {
            debugPrint('$NativeAd loaded.');
            setState(() {
              _nativeAdIsLoaded = true;
            });
          },
          onAdFailedToLoad: (ad, error) {
            // Dispose the ad here to free resources.
            debugPrint('$NativeAd failed to load: $error');
            ad.dispose();
          },
        ),
        request: const AdManagerAdRequest(),
        // Styling
        nativeTemplateStyle: NativeTemplateStyle(
            // Required: Choose a template.
            templateType: TemplateType.medium,
            // Optional: Customize the ad's style.
            mainBackgroundColor: Colors.purple,
            cornerRadius: 10.0,
            callToActionTextStyle: NativeTemplateTextStyle(
                textColor: Colors.cyan,
                backgroundColor: Colors.red,
                style: NativeTemplateFontStyle.monospace,
                size: 16.0),
            primaryTextStyle: NativeTemplateTextStyle(
                textColor: Colors.red,
                backgroundColor: Colors.cyan,
                style: NativeTemplateFontStyle.italic,
                size: 16.0),
            secondaryTextStyle: NativeTemplateTextStyle(
                textColor: Colors.green,
                backgroundColor: Colors.black,
                style: NativeTemplateFontStyle.bold,
                size: 16.0),
            tertiaryTextStyle: NativeTemplateTextStyle(
                textColor: Colors.brown,
                backgroundColor: Colors.amber,
                style: NativeTemplateFontStyle.normal,
                size: 16.0)))
      ..load();
  }
}

사용 가능한 스타일 지정 옵션은 NativeTemplateStyleNativeTemplateTextStyle를 참고하세요.

광고 맞춤설정

네이티브 템플릿을 사용하여 네이티브 광고를 맞춤설정하면 광고의 UI 구성이 NativeTemplateStyle 클래스에 상주하므로 Dart 코드로 전체 네이티브 광고의 스타일을 지정할 수 있습니다.

템플릿 크기

Flutter 네이티브 광고 템플릿은 TemplateType.smallTemplateType.medium의 두 가지 유형으로 제공됩니다. 작은 템플릿은 TableView 또는 GridView, 인피드 광고 등 얇은 직사각형 광고 보기가 필요한 모든 곳에 적합합니다. 중간 템플릿은 방문 페이지 또는 스플래시 페이지에 이상적인 0.5~3/4 페이지 뷰입니다.

작게

Android

iOS
보통

Android

iOS

네이티브 광고 이벤트

네이티브 광고 상호작용과 관련된 이벤트에 대한 알림을 받으려면 광고의 listener 속성을 사용하세요. 그런 다음 NativeAdListener를 구현하여 광고 이벤트 콜백을 수신합니다.

class NativeExampleState extends State<NativeExample> {
  NativeAd? _nativeAd;
  bool _nativeAdIsLoaded = false;

 // TODO: replace this test ad unit with your own ad unit.
 final _adUnitId = '/6499/example/native';

  /// Loads a native ad.
  void loadAd() {
    _nativeAd = NativeAd(
        adUnitId: _adUnitId,
        listener: NativeAdListener(
          onAdLoaded: (ad) {
            print('$NativeAd loaded.');
            setState(() {
              _nativeAdIsLoaded = true;
            });
          },
          onAdFailedToLoad: (ad, error) {
            // Dispose the ad here to free resources.
            print('$NativeAd failedToLoad: $error');
            ad.dispose();
          },
          // Called when a click is recorded for a NativeAd.
          onAdClicked: (ad) {},
          // Called when an impression occurs on the ad.
          onAdImpression: (ad) {},
          // Called when an ad removes an overlay that covers the screen.
          onAdClosed: (ad) {},
          // Called when an ad opens an overlay that covers the screen.
          onAdOpened: (ad) {},
          // For iOS only. Called before dismissing a full screen view
          onAdWillDismissScreen: (ad) {},
          // Called when an ad receives revenue value.
          onPaidEvent: (ad, valueMicros, precision, currencyCode) {},
        ),
        request: const AdManagerAdRequest(),
        // Styling
        nativeTemplateStyle: NativeTemplateStyle(
            // Required: Choose a template.
            templateType: TemplateType.medium,
            // Optional: Customize the ad's style.
            mainBackgroundColor: Colors.purple,
            cornerRadius: 10.0,
            callToActionTextStyle: NativeTemplateTextStyle(
                textColor: Colors.cyan,
                backgroundColor: Colors.red,
                style: NativeTemplateFontStyle.monospace,
                size: 16.0),
            primaryTextStyle: NativeTemplateTextStyle(
                textColor: Colors.red,
                backgroundColor: Colors.cyan,
                style: NativeTemplateFontStyle.italic,
                size: 16.0),
            secondaryTextStyle: NativeTemplateTextStyle(
                textColor: Colors.green,
                backgroundColor: Colors.black,
                style: NativeTemplateFontStyle.bold,
                size: 16.0),
            tertiaryTextStyle: NativeTemplateTextStyle(
                textColor: Colors.brown,
                backgroundColor: Colors.amber,
                style: NativeTemplateFontStyle.normal,
                size: 16.0)))
      ..load();
  }
}

디스플레이 광고

NativeAd를 위젯으로 표시하려면 load()를 호출한 후 지원되는 광고로 AdWidget를 인스턴스화해야 합니다. load()를 호출하기 전에 위젯을 만들 수 있지만 위젯 트리에 추가하기 전에 load()를 호출해야 합니다.

AdWidget는 Flutter의 Widget 클래스에서 상속되며 다른 위젯처럼 사용할 수 있습니다. iOS에서는 지정된 너비와 높이의 컨테이너에 위젯을 배치해야 합니다. 그렇지 않으면 광고가 게재되지 않을 수 있습니다.

// Small template
final adContainer = ConstrainedBox(
  constraints: const BoxConstraints(
    minWidth: 320, // minimum recommended width
    minHeight: 90, // minimum recommended height
    maxWidth: 400,
    maxHeight: 200,
  ),
  child: AdWidget(ad: _nativeAd!),
);

// Medium template
final adContainer = ConstrainedBox(
  constraints: const BoxConstraints(
    minWidth: 320, // minimum recommended width
    minHeight: 320, // minimum recommended height
    maxWidth: 400,
    maxHeight: 400,
  ),
  child: AdWidget(ad: _nativeAd!),
);

광고 삭제

NativeAd에 더 이상 액세스할 필요가 없으면 이 객체를 삭제해야 합니다. dispose()를 호출하는 경우에 대한 권장사항은 네이티브 광고와 연결된 AdWidget가 위젯 트리와 AdListener.onAdFailedToLoad() 콜백에서 삭제된 후입니다.