Dart 中的原生广告模板

原生广告模板是原生广告的完整代码视图,旨在加快广告植入速度并简化修改过程。借助原生广告模板,该插件可为您提供预构建的 Android 和 iOS 布局,并且您可以使用 Dart API 来自定义原生素材资源的样式。

本指南将介绍如何使用 Dart API 设置底层平台视图的样式并呈现广告。

前提条件

  • Flutter 2.4.0 或更高版本。

务必用测试广告进行测试

在构建和测试应用时,请确保使用的是测试广告,而不是实际投放的广告。对于原生广告,加载测试广告最简便的方法就是使用下面的专用测试广告单元 ID:

Android

ca-app-pub-3940256099942544/2247696110

iOS

ca-app-pub-3940256099942544/3986624511

测试广告单元配置为针对每个请求返回测试广告,因此您可以在编码、测试和调试时在自己的应用中使用它们 - 只需确保将其替换为您自己的广告单元 ID 即可,然后再发布应用。

加载广告

以下示例使用尺寸为 medium 的原生广告模板加载原生广告:

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

 // TODO: replace this test ad unit with your own ad unit.
 final String _adUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/2247696110'
      : 'ca-app-pub-3940256099942544/3986624511';

  /// 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 AdRequest(),
        // 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

定制广告

使用原生广告模板自定义原生广告时,广告的界面配置将位于 NativeTemplateStyle 类中,让您能够使用 Dart 代码为整个原生广告设置样式。

模板尺寸

Flutter 原生广告模板有两种类型:TemplateType.smallTemplateType.medium。小模板非常适合 TableViewGridView,适用于信息流广告,或需要细长方形广告视图的任何位置。中等模板占页面视图的一半到四分之三,非常适合着陆页或启动页。


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 String _adUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/2247696110'
      : 'ca-app-pub-3940256099942544/3986624511';

  /// 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 AdRequest(),
        // 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 作为 widget 显示,您必须在调用 load() 后使用受支持的广告实例化 AdWidget。您可以在调用 load() 之前创建 widget,但必须先调用 load(),然后才能将其添加到 widget 树。

AdWidget 继承自 Flutter 的 Widget 类,可以像任何其他 widget 一样使用。在 iOS 上,请确保将该 widget 放置在具有指定宽度和高度的容器中。否则,您的广告可能不会展示。

// 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() 的最佳做法是,在从 widget 树和 AdListener.onAdFailedToLoad() 回调中移除与原生广告相关联的 AdWidget 之后。

后续步骤

GitHub 上的完整示例

原生广告模板