Mẫu gốc trong Dart

Mẫu gốc là chế độ xem đoạn mã hoàn chỉnh cho quảng cáo gốc, được thiết kế để giúp bạn triển khai nhanh chóng và dễ dàng sửa đổi. Với các mẫu gốc, trình bổ trợ sẽ cung cấp bố cục Android và iOS tạo sẵn cho bạn, ngoài ra bạn có thể tuỳ chỉnh kiểu của thành phần gốc bằng cách sử dụng Dart API.

Hướng dẫn này minh hoạ cách sử dụng API Dart để tạo kiểu cho các khung hiển thị cơ bản của nền tảng và để hiển thị quảng cáo.

Điều kiện tiên quyết

  • Flutter 2.4.0 trở lên.

Luôn kiểm tra bằng quảng cáo thử nghiệm

Khi bạn tạo và thử nghiệm ứng dụng, hãy nhớ sử dụng quảng cáo thử nghiệm thay vì quảng cáo đang chạy trong thực tế. Cách dễ nhất để tải quảng cáo thử nghiệm là sử dụng mã đơn vị quảng cáo thử nghiệm dành riêng cho quảng cáo gốc:

Android

ca-app-pub-3940256099942544/2247696110

iOS

ca-app-pub-3940256099942544/3986624511

Đơn vị quảng cáo thử nghiệm được định cấu hình để trả về quảng cáo thử nghiệm cho mọi yêu cầu. Vì vậy, bạn có thể sử dụng các đơn vị quảng cáo này trong ứng dụng của mình khi lập trình, thử nghiệm và gỡ lỗi. Bạn chỉ cần nhớ thay thế các đơn vị quảng cáo đó bằng mã đơn vị quảng cáo của mình trước khi phát hành ứng dụng.

Tải quảng cáo

Sau đây là ví dụ tải một quảng cáo gốc bằng cách sử dụng mẫu gốc có kích thước 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();
  }
}

Hãy xem NativeTemplateStyleNativeTemplateTextStyle để biết các tuỳ chọn định kiểu có sẵn.

Tuỳ chỉnh quảng cáo

Khi tuỳ chỉnh quảng cáo gốc bằng các mẫu gốc, cấu hình giao diện người dùng của quảng cáo sẽ nằm trong lớp NativeTemplateStyle, cho phép bạn tạo kiểu cho toàn bộ quảng cáo gốc trong mã Dart.

Kích thước mẫu

Các mẫu quảng cáo gốc Flutter có hai loại: TemplateType.smallTemplateType.medium. Mẫu nhỏ là lựa chọn lý tưởng cho TableView hoặc GridView, đối với quảng cáo trong nguồn cấp dữ liệu hoặc bất cứ nơi nào bạn cần chế độ xem quảng cáo hình chữ nhật mỏng. Mẫu trung bình chiếm từ 1/2 đến 3/4 lượt xem trang, rất lý tưởng cho trang đích hoặc trang chờ.

Nhỏ

Android

iOS
Phương tiện

Android

iOS

Sự kiện quảng cáo gốc

Để nhận thông báo về những sự kiện có liên quan đến các lượt tương tác với quảng cáo gốc, hãy sử dụng thuộc tính listener của quảng cáo. Sau đó, hãy triển khai NativeAdListener để nhận lệnh gọi lại sự kiện quảng cáo.

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();
  }
}

Quảng cáo hiển thị

Để hiển thị NativeAd dưới dạng tiện ích, bạn phải tạo AdWidget bằng quảng cáo được hỗ trợ sau khi gọi load(). Bạn có thể tạo tiện ích trước khi gọi load(), nhưng bạn phải gọi load() trước khi thêm tiện ích đó vào cây tiện ích.

AdWidget kế thừa từ lớp Widget của Flutter và có thể được sử dụng như bất kỳ tiện ích nào khác. Trên iOS, hãy đảm bảo bạn đặt tiện ích này trong một vùng chứa đã chỉ định chiều rộng và chiều cao. Nếu không, quảng cáo của bạn có thể sẽ không hiển thị.

// 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!),
);

Loại bỏ quảng cáo

Bạn phải loại bỏ NativeAd khi không còn cần quyền truy cập vào đó. Phương pháp hay nhất về thời điểm gọi dispose() là sau khi AdWidget liên kết với quảng cáo gốc bị xoá khỏi cây tiện ích và trong lệnh gọi lại AdListener.onAdFailedToLoad().

Các bước tiếp theo

Ví dụ đầy đủ trên GitHub

Mẫu quảng cáo gốc