Dart 中的原生广告模板

请选择平台: Android iOS Flutter

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

本指南演示了如何使用 DART API 来设置底层平台视图的样式并呈现广告。

前提条件

  • Flutter 2.4.0 或更高版本。

务必用测试广告进行测试

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

  • /21775744923/example/native

这些 ID 已经过专门配置,可针对每个请求返回测试广告。您可以在编码、测试和调试期间,在自己的应用中随意使用这些 ID,不过请务必在发布应用之前,将这些 ID 替换为您自己的广告单元 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 = '/21775744923/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

自定义广告

使用原生广告模板自定义原生广告时,广告的界面配置将位于 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 _adUnitId = '/21775744923/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();
  }
}

展示广告

如需以 widget 形式展示 NativeAd,您在调用 load() 之后,必须实例化含有受支持广告的 AdWidget。您可以在调用 load() 之前创建 widget,但必须先调用 load(),然后才能将 widget 添加到 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(),最佳做法是在将与原生广告关联的 AdWidget 从 widget 树中移除后调用,以及在 AdListener.onAdFailedToLoad() 回调函数中调用。