1. Giới thiệu
Trong lớp học lập trình này, bạn sẽ triển khai một biểu ngữ AdMob và một quảng cáo gốc cùng dòng AdMob trong một ứng dụng Flutter.
Sản phẩm bạn sẽ tạo ra
Lớp học lập trình này hướng dẫn bạn cách triển khai biểu ngữ cùng dòng AdMob và quảng cáo gốc cùng dòng AdMob trong một ứng dụng Flutter bằng cách sử dụng trình bổ trợ Quảng cáo trên thiết bị di động của Google cho Flutter.
|
|
Nếu bạn gặp vấn đề (lỗi trong đoạn mã, lỗi ngữ pháp, từ ngữ không rõ ràng, v.v.) khi thực hành theo lớp học lập trình này, hãy báo cáo vấn đề bằng cách nhấp vào đường liên kết Báo cáo lỗi ở góc dưới bên trái của lớp học lập trình.
Kiến thức bạn sẽ học được
- Cách thiết lập trình bổ trợ Google Mobile Ads Flutter
- Cách triển khai quảng cáo biểu ngữ cùng dòng và quảng cáo có tặng thưởng trong ứng dụng Flutter
Bạn cần có
- Android Studio 4.1 trở lên
- Xcode 12 trở lên (để phát triển iOS)
Bạn đánh giá thế nào về mức độ kinh nghiệm của mình với AdMob?
Bạn đánh giá thế nào về trình độ kinh nghiệm của mình với Flutter?
2. Thiết lập môi trường phát triển Flutter
Bạn cần có 2 phần mềm để hoàn thành bài thực hành này: Flutter SDK và một trình chỉnh sửa.
Bạn có thể chạy lớp học lập trình này bằng bất kỳ thiết bị nào sau đây:
- Một thiết bị Android hoặc iOS thực được kết nối với máy tính và được đặt ở Chế độ nhà phát triển.
- Trình mô phỏng iOS (bạn cần cài đặt các công cụ Xcode).
- Trình mô phỏng Android (cần thiết lập trong Android Studio).
- Một trình duyệt (bạn cần có Chrome để gỡ lỗi).
- Dưới dạng ứng dụng máy tính cho Windows, Linux hoặc macOS. Bạn phải phát triển trên nền tảng mà bạn dự định triển khai. Vì vậy, nếu muốn phát triển một ứng dụng máy tính cho Windows, bạn phải phát triển trên Windows để truy cập vào chuỗi bản dựng thích hợp. Có những yêu cầu cụ thể theo hệ điều hành được đề cập chi tiết trên docs.flutter.dev/desktop.
Tải mã xuống
Sau khi tải tệp zip xuống, hãy giải nén nội dung của tệp đó. Bạn sẽ có một thư mục có tên admob-inline-ads-in-flutter-main.
Ngoài ra, bạn có thể sao chép kho lưu trữ GitHub từ dòng lệnh:
$ git clone https://github.com/googlecodelabs/admob-inline-ads-in-flutter
Kho lưu trữ này có 3 thư mục:
starter: Mã khởi đầu mà bạn sẽ tạo trong lớp học lập trình này.
complete: Mã hoàn chỉnh cho lớp học lập trình này. (Java và Objective-C cho mã gốc)
complete_kotlin_swift: Mã hoàn chỉnh cho lớp học lập trình này. (Kotlin và Swift cho mã gốc)
3. Thiết lập ứng dụng và đơn vị quảng cáo AdMob
Vì Flutter là một SDK đa nền tảng, nên bạn cần thêm một ứng dụng và đơn vị quảng cáo cho cả Android và iOS trong AdMob.
Thiết lập cho Android
Để thiết lập cho Android, bạn cần thêm một ứng dụng Android và tạo đơn vị quảng cáo.
Thêm ứng dụng Android
- Trong bảng điều khiển AdMob, hãy nhấp vào THÊM ỨNG DỤNG trong trình đơn Ứng dụng.
- Khi được hỏi Bạn đã xuất bản ứng dụng của mình trên Google Play hoặc App Store chưa?, hãy nhấp vào KHÔNG.
- Nhập
AdMob inline adsvào trường tên ứng dụng rồi chọn Android làm nền tảng.

- Bạn không cần bật chỉ số người dùng để hoàn tất lớp học lập trình này. Tuy nhiên, bạn nên làm việc này vì nó giúp bạn hiểu rõ hơn về hành vi của người dùng. Nhấp vào THÊM để hoàn tất quy trình.

Tạo đơn vị quảng cáo
Cách thêm đơn vị quảng cáo:
- Chọn ứng dụng Quảng cáo trong dòng AdMob trong trình đơn Ứng dụng trên bảng điều khiển AdMob.
- Nhấp vào trình đơn Đơn vị quảng cáo.
Biểu ngữ
|
|
Gốc
|
|
Thường mất vài giờ để một đơn vị quảng cáo mới có thể phân phát quảng cáo.
Nếu bạn muốn kiểm thử ngay hành vi của quảng cáo, hãy sử dụng mã ứng dụng và mã đơn vị quảng cáo thử nghiệm có trong bảng mã ứng dụng/mã đơn vị quảng cáo Android và mã ứng dụng/mã đơn vị quảng cáo iOS.
Thiết lập cho iOS
Để thiết lập cho iOS, bạn cần thêm một ứng dụng iOS và tạo đơn vị quảng cáo.
Thêm ứng dụng iOS
- Trong bảng điều khiển AdMob, hãy nhấp vào THÊM ỨNG DỤNG trong trình đơn Ứng dụng.
- Khi được hỏi Bạn đã xuất bản ứng dụng của mình trên Google Play hoặc App Store chưa?, hãy nhấp vào KHÔNG.
- Nhập
AdMob inline adsvào trường tên ứng dụng rồi chọn iOS làm nền tảng.

- Bạn không cần bật chỉ số người dùng để hoàn tất lớp học lập trình này. Tuy nhiên, bạn nên làm việc này vì nó giúp bạn hiểu rõ hơn về hành vi của người dùng. Nhấp vào THÊM để hoàn tất quy trình.

Tạo đơn vị quảng cáo
Cách thêm đơn vị quảng cáo:
- Chọn ứng dụng Quảng cáo trong dòng AdMob trong trình đơn Ứng dụng trên bảng điều khiển AdMob.
- Nhấp vào trình đơn Đơn vị quảng cáo.
Biểu ngữ
|
|
Gốc
|
|
Thường mất vài giờ để một đơn vị quảng cáo mới có thể phân phát quảng cáo.
Nếu bạn muốn kiểm tra ngay hành vi của quảng cáo, hãy sử dụng mã ứng dụng thử nghiệm và mã đơn vị quảng cáo được liệt kê trong bảng sau.
Không bắt buộc: Sử dụng ứng dụng AdMob và đơn vị quảng cáo thử nghiệm
Nếu muốn làm theo lớp học lập trình thay vì tự tạo ứng dụng và đơn vị quảng cáo mới, bạn có thể sử dụng mã ứng dụng AdMob và mã đơn vị quảng cáo thử nghiệm được liệt kê trong các bảng sau.
Mã ứng dụng Android/mã đơn vị quảng cáo
Item | mã ứng dụng/mã đơn vị quảng cáo |
Mã ứng dụng AdMob |
|
Biểu ngữ |
|
Mã gốc |
|
Mã ứng dụng/mã đơn vị quảng cáo iOS
Item | mã ứng dụng/mã đơn vị quảng cáo |
Mã ứng dụng AdMob |
|
Biểu ngữ |
|
Mã gốc |
|
Để biết thêm thông tin về quảng cáo thử nghiệm, hãy xem tài liệu dành cho nhà phát triển về quảng cáo thử nghiệm trên Android và quảng cáo thử nghiệm trên iOS.
4. Thêm trình bổ trợ Google Mobile Ads cho Flutter
Flutter sử dụng các trình bổ trợ để cung cấp quyền truy cập vào nhiều dịch vụ dành riêng cho nền tảng. Các trình bổ trợ cho phép bạn truy cập vào các dịch vụ và API trên mỗi nền tảng.
Trình bổ trợ google_mobile_ads hỗ trợ tải và hiển thị quảng cáo biểu ngữ, quảng cáo xen kẽ, quảng cáo có tặng thưởng và quảng cáo gốc bằng API AdMob.
Vì Flutter là một SDK đa nền tảng, nên trình bổ trợ google_mobile_ads có thể áp dụng cho cả iOS và Android. Vì vậy, nếu bạn thêm trình bổ trợ này vào ứng dụng Flutter, thì cả phiên bản Android và iOS của ứng dụng quảng cáo trong dòng AdMob đều sẽ sử dụng trình bổ trợ này.
Thêm trình bổ trợ Google Mobile Ads làm phần phụ thuộc
Để truy cập vào các API AdMob từ dự án quảng cáo AdMob trong dòng, hãy thêm google_mobile_ads làm phần phụ thuộc vào tệp pubspec.yaml nằm ở thư mục gốc của dự án.
pubspec.yaml
...
dependencies:
flutter:
sdk: flutter
google_fonts: ^0.3.9
# TODO: Add google_mobile_ads as a dependency
google_mobile_ads: ^1.2.0
...
Nhấp vào Pub get để cài đặt trình bổ trợ trong dự án Quảng cáo trong dòng AdMob.

Cập nhật tệp AndroidManifest.xml (Android)
- Mở tệp
android/app/src/main/AndroidManifest.xmltrong Android Studio. - Thêm mã ứng dụng AdMob bằng cách thêm thẻ
<meta-data>có tên làcom.google.android.gms.ads.APPLICATION_ID. Ví dụ: nếu mã ứng dụng AdMob của bạn làca-app-pub-3940256099942544~3347511713, thì bạn cần thêm các dòng sau vào tệpAndroidManifest.xml.
AndroidManifest.xml
<manifest>
...
<application>
...
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/>
</application>
</manifest>
Cập nhật Info.plist (iOS)
- Mở tệp
ios/Runner/Info.plisttrong Android Studio. - Thêm khoá
GADApplicationIdentifiercó giá trị chuỗi là mã ứng dụng AdMob của bạn. Ví dụ: nếu mã ứng dụng AdMob của bạn làca-app-pub-3940256099942544~1458002511, thì bạn cần thêm các dòng sau vào tệpInfo.plist.
ios/Runner/Info.plist
...
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
...
5. Thêm một lớp trợ giúp cho quảng cáo
Tạo một tệp mới có tên ad_helper.dart trong thư mục lib. Sau đó, hãy triển khai lớp AdHelper. Lớp này cung cấp mã ứng dụng AdMob và mã đơn vị quảng cáo cho Android và iOS.
Đảm bảo rằng bạn thay thế mã ứng dụng AdMob (ca-app-pub-xxxxxx~yyyyy) và mã đơn vị quảng cáo (ca-app-pub-xxxxxxx/yyyyyyyy) bằng các mã nhận dạng mà bạn đã tạo trong bước trước.
ad_helper.dart
import 'dart:io';
class AdHelper {
static String get bannerAdUnitId {
if (Platform.isAndroid) {
return "<YOUR_ANDROID_BANNER_AD_UNIT_ID";
} else if (Platform.isIOS) {
return "<YOUR_IOS_BANNER_AD_UNIT_ID>";
} else {
throw UnsupportedError("Unsupported platform");
}
}
static String get nativeAdUnitId {
if (Platform.isAndroid) {
return "<YOUR_ANDROID_NATIVE_AD_UNIT_ID>";
} else if (Platform.isIOS) {
return "<YOUR_IOS_NATIVE_AD_UNIT_ID>";
} else {
throw UnsupportedError("Unsupported platform");
}
}
}
Hãy sử dụng đoạn mã sau nếu bạn muốn sử dụng mã ứng dụng AdMob thử nghiệm và mã đơn vị quảng cáo thử nghiệm.
ad_helper.dart
import 'dart:io';
class AdHelper {
static String get bannerAdUnitId {
if (Platform.isAndroid) {
return 'ca-app-pub-3940256099942544/6300978111';
} else if (Platform.isIOS) {
return 'ca-app-pub-3940256099942544/2934735716';
}
throw UnsupportedError("Unsupported platform");
}
static String get nativeAdUnitId {
if (Platform.isAndroid) {
return 'ca-app-pub-3940256099942544/2247696110';
} else if (Platform.isIOS) {
return 'ca-app-pub-3940256099942544/3986624511';
}
throw UnsupportedError("Unsupported platform");
}
}
6. Khởi chạy SDK Quảng cáo của Google trên thiết bị di động
Trước khi tải quảng cáo, bạn cần khởi chạy SDK Quảng cáo của Google trên thiết bị di động. Mở tệp lib/home_page.dart rồi sửa đổi _initGoogleMobileAds() để khởi chạy SDK trước khi trang chủ được tải.
Xin lưu ý rằng bạn cần thay đổi kiểu dữ liệu trả về của phương thức _initGoogleMobileAds() từ Future<dynamic> thành Future<InitializationStatus> để nhận được kết quả khởi chạy SDK sau khi hoàn tất.
home_page.dart
// TODO: Import google_mobile_ads.dart
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/material.dart';
...
class HomePage extends StatelessWidget {
...
Future<InitializationStatus> _initGoogleMobileAds() {
// TODO: Initialize Google Mobile Ads SDK
return MobileAds.instance.initialize();
}
}
7. Thêm quảng cáo biểu ngữ
Trong phần này, bạn sẽ hiển thị một quảng cáo biểu ngữ ở giữa danh sách, như trong ảnh chụp màn hình sau.

- Mở tệp
lib/banner_inline_page.dart. - Nhập
ad_helper.dartvàgoogle_mobile_ads.dartbằng cách thêm các dòng sau:
banner_inline_page.dart
...
// TODO: Import ad_helper.dart
import 'package:admob_inline_ads_in_flutter/ad_helper.dart';
// TODO: Import google_mobile_ads.dart
import 'package:google_mobile_ads/google_mobile_ads.dart';
class BannerInlinePage extends StatefulWidget {
...
}
- Trong lớp
_BannerInlinePageState, hãy thêm các thành phần và phương thức sau cho một quảng cáo biểu ngữ.
Xin lưu ý rằng _kAdIndex cho biết chỉ mục nơi quảng cáo biểu ngữ sẽ xuất hiện và được dùng để tính chỉ mục mục từ phương thức _getDestinationItemIndex().
banner_inline_page.dart
class _BannerInlinePageState extends State<BannerInlinePage> {
// TODO: Add _kAdIndex
static final _kAdIndex = 4;
// TODO: Add a banner ad instance
BannerAd? _ad;
...
// TODO: Add _getDestinationItemIndex()
int _getDestinationItemIndex(int rawIndex) {
if (rawIndex >= _kAdIndex && _ad != null) {
return rawIndex - 1;
}
return rawIndex;
}
...
}
- Trong phương thức
initState(), hãy tạo và tải mộtBannerAdcho biểu ngữ 320x50 (AdSize.banner). Xin lưu ý rằng bạn phải định cấu hình một trình nghe sự kiện quảng cáo để cập nhật giao diện người dùng (setState()) khi một quảng cáo được tải.
banner_inline_page.dart
@override
void initState() {
super.initState();
// TODO: Load a banner ad
BannerAd(
adUnitId: AdHelper.bannerAdUnitId,
size: AdSize.banner,
request: AdRequest(),
listener: BannerAdListener(
onAdLoaded: (ad) {
setState(() {
_ad = ad as BannerAd;
});
},
onAdFailedToLoad: (ad, error) {
// Releases an ad resource when it fails to load
ad.dispose();
print('Ad load failed (code=${error.code} message=${error.message})');
},
),
).load();
}
- Sửa đổi phương thức
build()để hiển thị quảng cáo biểu ngữ khi có. - Cập nhật
itemCount,để tính một mục nhập quảng cáo biểu ngữ và cập nhậtitemBuilder,để hiển thị một quảng cáo biểu ngữ tại chỉ mục quảng cáo (_kAdIndex) khi quảng cáo được tải. - Cập nhật mã để sử dụng phương thức
_getDestinationItemIndex()nhằm truy xuất chỉ mục cho mục nội dung.
banner_inline_page.dart
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: ListView.builder(
// TODO: Adjust itemCount based on the ad load state
itemCount: widget.entries.length + (_ad != null ? 1 : 0),
itemBuilder: (context, index) {
// TODO: Render a banner ad
if (_ad != null && index == _kAdIndex) {
return Container(
width: _ad!.size.width.toDouble(),
height: 72.0,
alignment: Alignment.center,
child: AdWidget(ad: _ad!),
);
} else {
// TODO: Get adjusted item index from _getDestinationItemIndex()
final item = widget.entries[_getDestinationItemIndex(index)];
return ListTile(
...
);
}
},
),
);
}
- Giải phóng tài nguyên được liên kết với đối tượng
BannerAdbằng cách gọi phương thứcBannerAd.dispose()trong phương thức gọi lạidispose().
banner_inline_page.dart
@override
void dispose() {
// TODO: Dispose a BannerAd object
_ad?.dispose();
super.dispose();
}
Vậy là xong! Chạy dự án rồi nhấp vào nút Banner inline ad (Quảng cáo cùng dòng biểu ngữ) trên Trang chủ. Sau khi quảng cáo được tải, bạn sẽ thấy một quảng cáo biểu ngữ ở giữa danh sách.

8. Thêm quảng cáo gốc
Trong phần này, bạn sẽ hiển thị một quảng cáo gốc ở giữa danh sách, như minh hoạ trong ảnh chụp màn hình sau.

Quảng cáo gốc hiển thị cho người dùng bằng các thành phần giao diện người dùng vốn có của nền tảng (ví dụ: View trên Android hoặc UIView trên iOS).
Tuy nhiên, bạn không thể tạo trực tiếp các thành phần giao diện người dùng gốc bằng cách sử dụng các tiện ích Flutter. Vì vậy, bạn phải triển khai một NativeAdFactory cho mỗi nền tảng. NativeAdFactory này được dùng để tạo một khung hiển thị quảng cáo gốc dành riêng cho nền tảng (NativeAdView trên Android và GADNativeAdView trên iOS) từ một đối tượng quảng cáo gốc (NativeAd trên Android và GADNativeAd trên iOS).
Triển khai NativeAdFactory cho Android (Java)
- Mở tệp
android/build.gradle(hoặc bất kỳ tệp nào trong thư mục android), rồi nhấp vào Open for Editing in Android Studio (Mở để chỉnh sửa trong Android Studio) để mở một dự án Android.

- Nếu bạn được yêu cầu chọn một cửa sổ để mở dự án mới, hãy nhấp vào New Window (Cửa sổ mới) để dự án Flutter vẫn mở trong khi bạn đang làm việc trên dự án Android.

Tạo bố cục quảng cáo gốc
- Khi dự án Android đang mở, hãy nhấp chuột phải vào app trong ngăn dự án của Android Studio, rồi chọn New > Android Resource File (Mới > Tệp tài nguyên Android) trong trình đơn theo bối cảnh.

- Trong hộp thoại New Resource File (Tệp tài nguyên mới), hãy nhập
list_tile_native_ad.xmllàm tên tệp. - Chọn Layout làm loại tài nguyên và nhập
com.google.android.gms.ads.nativead.NativeAdViewlàm phần tử gốc. - Nhấp vào OK để tạo một tệp bố cục mới.

- Triển khai bố cục quảng cáo như sau. Xin lưu ý rằng bố cục phải phù hợp với thiết kế trực quan của trải nghiệm người dùng cho nền tảng mà bố cục đó hướng đến.
list_tile_native_ad.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.ads.nativead.NativeAdView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_list_tile_native_ad_attribution_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#F19938"
android:text="Ad"
android:textColor="#FFFFFF"
android:textSize="12sp" />
<ImageView
android:id="@+id/iv_list_tile_native_ad_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:scaleType="fitXY"
tools:background="#EDEDED" />
<TextView
android:id="@+id/tv_list_tile_native_ad_attribution_large"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:background="#F19938"
android:gravity="center"
android:text="Ad"
android:textColor="#FFFFFF"
android:visibility="invisible" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="80dp"
android:layout_marginLeft="80dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="@+id/tv_list_tile_native_ad_headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:maxLines="1"
android:textColor="#000000"
android:textSize="16sp"
tools:text="Headline" />
<TextView
android:id="@+id/tv_list_tile_native_ad_body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:maxLines="1"
android:textColor="#828282"
android:textSize="14sp"
tools:text="body" />
</LinearLayout>
</FrameLayout>
</com.google.android.gms.ads.nativead.NativeAdView>
Tạo lớp ListTileNativeAdFactory
- Trong ngăn Project (Dự án), hãy nhấp chuột phải vào gói com.codelab.flutter.admobinlineads rồi chọn New > Java Class (Mới > Lớp Java).

- Nhập
ListTileNativeAdFactorylàm tên rồi chọn Class (Lớp) trong danh sách.

- Sau khi hộp thoại New Class (Lớp mới) xuất hiện, hãy để trống mọi thứ rồi nhấp vào OK.
Bạn sẽ thấy lớp ListTileNativeAdFactory được tạo trong gói com.codelab.flutter.admobinlineads.

- Triển khai lớp
ListTileNativeAdFactorynhư sau. Xin lưu ý rằng lớp này sẽ triển khai phương thứccreateNativeAd()trong giao diệnGoogleMobileAdsPlugin.NativeAdFactory.
Lớp nhà máy chịu trách nhiệm tạo một đối tượng khung hiển thị để hiển thị quảng cáo gốc. Như bạn có thể thấy trong mã, lớp nhà máy sẽ tạo một UnifiedNativeAdView và điền sẵn đối tượng NativeAd.
ListTileNativeAdFactory.java
// TODO: Implement ListTileNativeAdFactory class
package com.codelab.flutter.admobinlineads;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Map;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin;
class ListTileNativeAdFactory implements GoogleMobileAdsPlugin.NativeAdFactory {
private final Context context;
ListTileNativeAdFactory(Context context) {
this.context = context;
}
@Override
public NativeAdView createNativeAd(
NativeAd nativeAd, Map<String, Object> customOptions) {
NativeAdView nativeAdView = (NativeAdView) LayoutInflater.from(context)
.inflate(R.layout.list_tile_native_ad, null);
TextView attributionViewSmall = nativeAdView
.findViewById(R.id.tv_list_tile_native_ad_attribution_small);
TextView attributionViewLarge = nativeAdView
.findViewById(R.id.tv_list_tile_native_ad_attribution_large);
ImageView iconView = nativeAdView.findViewById(R.id.iv_list_tile_native_ad_icon);
NativeAd.Image icon = nativeAd.getIcon();
if (icon != null) {
attributionViewSmall.setVisibility(View.VISIBLE);
attributionViewLarge.setVisibility(View.INVISIBLE);
iconView.setImageDrawable(icon.getDrawable());
} else {
attributionViewSmall.setVisibility(View.INVISIBLE);
attributionViewLarge.setVisibility(View.VISIBLE);
}
nativeAdView.setIconView(iconView);
TextView headlineView = nativeAdView.findViewById(R.id.tv_list_tile_native_ad_headline);
headlineView.setText(nativeAd.getHeadline());
nativeAdView.setHeadlineView(headlineView);
TextView bodyView = nativeAdView.findViewById(R.id.tv_list_tile_native_ad_body);
bodyView.setText(nativeAd.getBody());
bodyView.setVisibility(nativeAd.getBody() != null ? View.VISIBLE : View.INVISIBLE);
nativeAdView.setBodyView(bodyView);
nativeAdView.setNativeAd(nativeAd);
return nativeAdView;
}
}
Đăng ký lớp ListTileNativeAdFactory
Bạn phải đăng ký một thực thể của NativeAdFactory với GoogleMobileAdsPlugin thì mới có thể sử dụng thực thể đó từ phía Flutter.
- Mở tệp
MainActivity.java, rồi ghi đè phương thứcconfigureFlutterEngine()và phương thứccleanUpFlutterEngine(). - Đăng ký lớp
ListTileNativeAdFactorybằng một mã nhận dạng chuỗi riêng biệt (listTile) trong phương thứcconfigureFlutterEngine().
MainActivity.java
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
// TODO: Register the ListTileNativeAdFactory
GoogleMobileAdsPlugin.registerNativeAdFactory(flutterEngine, "listTile",
new ListTileNativeAdFactory(getContext()));
}
...
}
- Mọi phiên bản
NativeAdFactoryđều phải được huỷ đăng ký trong quá trình dọn dẹp. Huỷ đăng ký lớpListTileNativeAdFactorytrong phương thứccleanUpFlutterEngine().
MainActivity.java
public class MainActivity extends FlutterActivity {
...
@Override
public void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.cleanUpFlutterEngine(flutterEngine);
// TODO: Unregister the ListTileNativeAdFactory
GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "listTile");
}
}
Giờ đây, bạn đã sẵn sàng sử dụng lớp ListTileNativeAdFactory để hiển thị quảng cáo gốc trên Android.
Triển khai NativeAdFactory cho Android (Kotlin)
- Mở tệp
android/build.gradle(hoặc bất kỳ tệp nào trong thư mục android), rồi nhấp vào Open for Editing in Android Studio (Mở để chỉnh sửa trong Android Studio) để mở một dự án Android.

- Nếu bạn được yêu cầu chọn một cửa sổ để mở dự án mới, hãy nhấp vào New Window (Cửa sổ mới) để dự án Flutter vẫn mở trong khi bạn đang làm việc trên dự án Android.

Tạo bố cục quảng cáo gốc
- Khi dự án Android đang mở, hãy nhấp chuột phải vào app trong ngăn dự án của Android Studio, rồi chọn New > Android Resource File (Mới > Tệp tài nguyên Android) trong trình đơn theo bối cảnh.

- Trong hộp thoại New Resource File (Tệp tài nguyên mới), hãy nhập
list_tile_native_ad.xmllàm tên tệp. - Chọn Layout làm loại tài nguyên và nhập
com.google.android.gms.ads.nativead.NativeAdViewlàm phần tử gốc. - Nhấp vào OK để tạo một tệp bố cục mới.

- Triển khai bố cục quảng cáo như sau. Xin lưu ý rằng bố cục phải phù hợp với thiết kế trực quan của trải nghiệm người dùng cho nền tảng mà bố cục đó hướng đến.
list_tile_native_ad.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.ads.nativead.NativeAdView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_list_tile_native_ad_attribution_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#F19938"
android:text="Ad"
android:textColor="#FFFFFF"
android:textSize="12sp" />
<ImageView
android:id="@+id/iv_list_tile_native_ad_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:scaleType="fitXY"
tools:background="#EDEDED" />
<TextView
android:id="@+id/tv_list_tile_native_ad_attribution_large"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:background="#F19938"
android:gravity="center"
android:text="Ad"
android:textColor="#FFFFFF"
android:visibility="invisible" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="80dp"
android:layout_marginLeft="80dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="@+id/tv_list_tile_native_ad_headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:maxLines="1"
android:textColor="#000000"
android:textSize="16sp"
tools:text="Headline" />
<TextView
android:id="@+id/tv_list_tile_native_ad_body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:maxLines="1"
android:textColor="#828282"
android:textSize="14sp"
tools:text="body" />
</LinearLayout>
</FrameLayout>
</com.google.android.gms.ads.nativead.NativeAdView>
Tạo lớp ListTileNativeAdFactory
- Trong ngăn Project (Dự án), hãy nhấp chuột phải vào gói com.codelab.flutter.admobinlineads rồi chọn New > Kotlin File/Class (Mới > Lớp/Tệp Kotlin).

- Nhập
ListTileNativeAdFactorylàm tên rồi chọn Class (Lớp) trong danh sách.

- Bạn sẽ thấy lớp
ListTileNativeAdFactoryđược tạo trong góicom.codelab.flutter.admobinlineads. - Triển khai lớp
ListTileNativeAdFactorynhư sau. Xin lưu ý rằng lớp này sẽ triển khai phương thứccreateNativeAd()trong giao diệnGoogleMobileAdsPlugin.NativeAdFactory.
Lớp nhà máy chịu trách nhiệm tạo một đối tượng khung hiển thị để hiển thị quảng cáo gốc. Như bạn có thể thấy trong mã, lớp nhà máy sẽ tạo một NativeAdView và điền sẵn đối tượng NativeAd.
ListTileNativeAdFactory.kt
// TODO: Implement ListTileNativeAdFactory class
package com.codelab.flutter.admobinlineads
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdView
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin
class ListTileNativeAdFactory(val context: Context) : GoogleMobileAdsPlugin.NativeAdFactory {
override fun createNativeAd(
nativeAd: NativeAd,
customOptions: MutableMap<String, Any>?
): NativeAdView {
val nativeAdView = LayoutInflater.from(context)
.inflate(R.layout.list_tile_native_ad, null) as NativeAdView
with(nativeAdView) {
val attributionViewSmall =
findViewById<TextView>(R.id.tv_list_tile_native_ad_attribution_small)
val attributionViewLarge =
findViewById<TextView>(R.id.tv_list_tile_native_ad_attribution_large)
val iconView = findViewById<ImageView>(R.id.iv_list_tile_native_ad_icon)
val icon = nativeAd.icon
if (icon != null) {
attributionViewSmall.visibility = View.VISIBLE
attributionViewLarge.visibility = View.INVISIBLE
iconView.setImageDrawable(icon.drawable)
} else {
attributionViewSmall.visibility = View.INVISIBLE
attributionViewLarge.visibility = View.VISIBLE
}
this.iconView = iconView
val headlineView = findViewById<TextView>(R.id.tv_list_tile_native_ad_headline)
headlineView.text = nativeAd.headline
this.headlineView = headlineView
val bodyView = findViewById<TextView>(R.id.tv_list_tile_native_ad_body)
with(bodyView) {
text = nativeAd.body
visibility = if (nativeAd.body.isNotEmpty()) View.VISIBLE else View.INVISIBLE
}
this.bodyView = bodyView
setNativeAd(nativeAd)
}
return nativeAdView
}
}
Đăng ký lớp ListTileNativeAdFactory
Bạn phải đăng ký một thực thể của NativeAdFactory với GoogleMobileAdsPlugin thì mới có thể sử dụng thực thể đó từ phía Flutter.
- Mở tệp
MainActivity.kt, rồi ghi đè phương thứcconfigureFlutterEngine()và phương thứccleanUpFlutterEngine(). - Đăng ký lớp
ListTileNativeAdFactorybằng một mã nhận dạng chuỗi riêng biệt (listTile) trong phương thứcconfigureFlutterEngine().
MainActivity.kt
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// TODO: Register the ListTileNativeAdFactory
GoogleMobileAdsPlugin.registerNativeAdFactory(
flutterEngine, "listTile", ListTileNativeAdFactory(context))
}
...
}
- Mọi phiên bản
NativeAdFactoryđều phải được huỷ đăng ký trong quá trình dọn dẹp. Huỷ đăng ký lớpListTileNativeAdFactorytrong phương thứccleanUpFlutterEngine().
MainActivity.kt
class MainActivity: FlutterActivity() {
...
override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
super.cleanUpFlutterEngine(flutterEngine)
// TODO: Unregister the ListTileNativeAdFactory
GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "listTile")
}
}
Giờ đây, bạn đã sẵn sàng sử dụng lớp ListTileNativeAdFactory để hiển thị quảng cáo gốc trên Android.
Triển khai NativeAdFactory cho iOS (Objective-C)
Mở tệp ios/Podfile (hoặc bất kỳ tệp nào trong thư mục ios), rồi nhấp vào Open iOS module in Xcode (Mở mô-đun iOS trong Xcode) để mở một dự án iOS.

Chuẩn bị bố cục quảng cáo gốc
Bạn cần có một khung hiển thị tuỳ chỉnh (*.xib) để bố trí các thành phần quảng cáo gốc. Trong lớp học lập trình này, bạn sẽ dùng khung hiển thị được định cấu hình sẵn để giảm thiểu công sức.
Khi dự án iOS được mở trong Xcode, hãy xác nhận rằng ListTileNativeAdView.xib có trong dự án Runner.

Tạo lớp ListTileNativeAdFactory
- Trong trình điều hướng dự án, hãy nhấp chuột phải vào nhóm Runner rồi chọn New File (Tệp mới) để tạo một tệp tiêu đề cho lớp mới.

- Trong hộp thoại mẫu, hãy chọn Header File (Tệp tiêu đề) rồi đặt tên là
ListTileNativeAdFactory. - Sau khi tạo tệp
ListTileNativeAdFactory.h, hãy xác định lớpListNativeAdFactorynhư sau:
ListTileNativeAdFactory.h
#ifndef ListTileNativeAdFactory_h
#define ListTileNativeAdFactory_h
// TODO: Import FLTGoogleMobileAdsPlugin.h
#import "FLTGoogleMobileAdsPlugin.h"
// TODO: Declare ListTileNativeAdFactory
@interface ListTileNativeAdFactory : NSObject<FLTNativeAdFactory>
@end
#endif /* ListTileNativeAdFactory_h */
- Tạo một tệp Objective-C bằng cách chọn New File (Tệp mới) trong nhóm Runner (Trình chạy).
- Trong hộp thoại tiếp theo, hãy nhập
ListTileNativeAdFactoryvào trường File (Tệp) rồi chọn Empty File (Tệp trống) làm loại tệp.

- Sau khi nhấp vào Tiếp theo, bạn sẽ được yêu cầu chọn một thư mục để tạo tệp mới. Giữ nguyên mọi thứ rồi nhấp vào Tạo.

- Triển khai lớp
ListTileNativeFactorynhư sau. Xin lưu ý rằng lớp này sẽ triển khai phương thứccreateNativeAd()trong giao thứcFLTNativeAdFactory.
Lớp nhà máy chịu trách nhiệm tạo một đối tượng khung hiển thị để hiển thị quảng cáo gốc. Như bạn có thể thấy trong mã, lớp nhà máy sẽ tạo một GADNativeAdView và điền sẵn đối tượng GADNativeAd.
ListTileNativeAdFactory.m
// TODO: Import ListTileNativeAdFactory.h
#import "ListTileNativeAdFactory.h"
// TODO: Implement ListTileNativeAdFactory
@implementation ListTileNativeAdFactory
- (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd
customOptions:(NSDictionary *)customOptions {
GADNativeAdView *nativeAdView =
[[NSBundle mainBundle] loadNibNamed:@"ListTileNativeAdView" owner:nil options:nil].firstObject;
((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;
((UILabel *)nativeAdView.bodyView).text = nativeAd.body;
nativeAdView.bodyView.hidden = nativeAd.body ? NO : YES;
((UIImageView *)nativeAdView.iconView).image = nativeAd.icon.image;
nativeAdView.iconView.hidden = nativeAd.icon ? NO : YES;
nativeAdView.callToActionView.userInteractionEnabled = NO;
nativeAdView.nativeAd = nativeAd;
return nativeAdView;
}
@end
Đăng ký lớp ListTileNativeAdFacotry
Bạn phải đăng ký một quy trình triển khai FLTNativeAdFactory với FLTGoogleMobileAdsPlugin thì mới có thể sử dụng quy trình đó từ phía Flutter.
Mở tệp AppDelegate.m rồi đăng ký ListTileNativeAdFactory bằng một mã nhận dạng chuỗi riêng biệt (listTile) bằng cách gọi phương thức [FLTGoogleMobileAdsPlugin registerNativeAdFactory].
AppDelegate.m
#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
// TODO: Import ListTileNativeAdFactory.h
#import "ListTileNativeAdFactory.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// TODO: Register ListTileNativeAdFactory
ListTileNativeAdFactory *listTileFactory = [[ListTileNativeAdFactory alloc] init];
[FLTGoogleMobileAdsPlugin registerNativeAdFactory:self
factoryId:@"listTile"
nativeAdFactory:listTileFactory];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
Giờ đây, bạn đã sẵn sàng sử dụng ListTileNativeAdFactory để hiển thị quảng cáo gốc trên iOS.
Triển khai NativeAdFactory cho iOS (Swift)
Mở tệp ios/Podfile (hoặc bất kỳ tệp nào trong thư mục ios), rồi nhấp vào Open iOS module in Xcode (Mở mô-đun iOS trong Xcode) để mở một dự án iOS.

Chuẩn bị bố cục quảng cáo gốc
Bạn cần có một khung hiển thị tuỳ chỉnh (*.xib) để bố trí các thành phần quảng cáo gốc. Trong lớp học lập trình này, bạn sẽ dùng khung hiển thị được định cấu hình sẵn để giảm thiểu công sức.
Khi dự án iOS được mở trong Xcode, hãy xác nhận rằng ListTileNativeAdView.xib có trong dự án Runner.

Tạo lớp ListTileNativeAdFactory
- Trong trình điều hướng dự án, hãy nhấp chuột phải vào nhóm Runner rồi chọn New File (Tệp mới) để tạo một tệp tiêu đề cho lớp mới.

- Trong hộp thoại mẫu, hãy chọn Swift File (Tệp Swift) rồi đặt tên là
ListTileNativeAdFactory. - Sau khi tạo tệp
ListTileNativeAdFactory.swift, hãy triển khai lớpListNativeAdFactory.
Xin lưu ý rằng lớp này sẽ triển khai phương thức createNativeAd() trong giao thức FLTNativeAdFactory.
Lớp nhà máy chịu trách nhiệm tạo một đối tượng khung hiển thị để hiển thị quảng cáo gốc. Như bạn có thể thấy trong mã, lớp nhà máy sẽ tạo một GADNativeAdView và điền sẵn đối tượng GADNativeAd.
ListTileNativeAdFactory.swift
// TODO: Import google_mobile_ads
import google_mobile_ads
// TODO: Implement ListTileNativeAdFactory
class ListTileNativeAdFactory : FLTNativeAdFactory {
func createNativeAd(_ nativeAd: GADNativeAd,
customOptions: [AnyHashable : Any]? = nil) -> GADNativeAdView? {
let nibView = Bundle.main.loadNibNamed("ListTileNativeAdView", owner: nil, options: nil)!.first
let nativeAdView = nibView as! GADNativeAdView
(nativeAdView.headlineView as! UILabel).text = nativeAd.headline
(nativeAdView.bodyView as! UILabel).text = nativeAd.body
nativeAdView.bodyView!.isHidden = nativeAd.body == nil
(nativeAdView.iconView as! UIImageView).image = nativeAd.icon?.image
nativeAdView.iconView!.isHidden = nativeAd.icon == nil
nativeAdView.callToActionView?.isUserInteractionEnabled = false
nativeAdView.nativeAd = nativeAd
return nativeAdView
}
}
Đăng ký lớp ListTileNativeAdFacotry
Bạn phải đăng ký một quy trình triển khai FLTNativeAdFactory với FLTGoogleMobileAdsPlugin thì mới có thể sử dụng quy trình đó từ phía Flutter.
Mở tệp AppDelegate.m rồi đăng ký ListTileNativeAdFactory bằng một mã nhận dạng chuỗi riêng biệt (listTile) bằng cách gọi phương thức FLTGoogleMobileAdsPlugin.registerNativeAdFactory().
AppDelegate.swift
import UIKit
import Flutter
// TODO: Import google_mobile_ads
import google_mobile_ads
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// TODO: Register ListTileNativeAdFactory
let listTileFactory = ListTileNativeAdFactory()
FLTGoogleMobileAdsPlugin.registerNativeAdFactory(
self, factoryId: "listTile", nativeAdFactory: listTileFactory)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Giờ đây, bạn đã sẵn sàng sử dụng ListTileNativeAdFactory để hiển thị quảng cáo gốc trên iOS.
Tích hợp quảng cáo gốc với các tiện ích Flutter
- Mở tệp
lib/native_inline_page.dart. Sau đó, hãy nhậpad_helper.dartvàgoogle_mobile_ads.dartbằng cách thêm các dòng sau:
native_inline_page.dart
...
// TODO: Import ad_helper.dart
import 'package:admob_inline_ads_in_flutter/ad_helper.dart';
// TODO: Import google_mobile_ads.dart
import 'package:google_mobile_ads/google_mobile_ads.dart';
class NativeInlinePage extends StatefulWidget {
...
}
- Trong lớp
_NativeInlinePageState, hãy thêm các thành phần và phương thức sau cho quảng cáo gốc.
Xin lưu ý rằng _kAdIndex cho biết chỉ mục nơi quảng cáo biểu ngữ sẽ xuất hiện và được dùng để tính chỉ mục mục từ phương thức _getDestinationItemIndex().
native_inline_page.dart
class _NativeInlinePageState extends State<NativeInlinePage> {
// TODO: Add _kAdIndex
static final _kAdIndex = 4;
// TODO: Add a native ad instance
NativeAd? _ad;
...
// TODO: Add _getDestinationItemIndex()
int _getDestinationItemIndex(int rawIndex) {
if (rawIndex >= _kAdIndex && _ad != null) {
return rawIndex - 1;
}
return rawIndex;
}
...
}
- Trong phương thức
initState(), hãy tạo và tải mộtNativeAdsử dụngListTileNativeAdFactoryđể tạo một khung hiển thị quảng cáo gốc.
Xin lưu ý rằng bạn sẽ dùng cùng một mã nhận dạng nhà máy (listTile) đã dùng để đăng ký nhà máy với trình bổ trợ.
native_inline_page.dart
@override
void initState() {
super.initState();
// TODO: Create a NativeAd instance
_ad = NativeAd(
adUnitId: AdHelper.nativeAdUnitId,
factoryId: 'listTile',
request: AdRequest(),
listener: NativeAdListener(
onAdLoaded: (ad) {
setState(() {
_ad = ad as NativeAd;
});
},
onAdFailedToLoad: (ad, error) {
// Releases an ad resource when it fails to load
ad.dispose();
print('Ad load failed (code=${error.code} message=${error.message})'); },
),
);
_ad.load();
}
- Sửa đổi phương thức
build()để hiển thị quảng cáo biểu ngữ khi có. - Cập nhật
itemCount,để tính một mục nhập quảng cáo biểu ngữ và cập nhậtitemBuilder,để hiển thị một quảng cáo biểu ngữ tại chỉ mục quảng cáo (_kAdIndex) khi quảng cáo được tải. - Cập nhật mã để sử dụng phương thức
_getDestinationItemIndex()nhằm truy xuất chỉ mục cho mục nội dung.
native_inline_page.dart
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: ListView.builder(
// TODO: Adjust itemCount based on the ad load state
itemCount: widget.entries.length + (_ad != null ? 1 : 0),
itemBuilder: (context, index) {
// TODO: Render a banner ad
if (_ad != null && index == _kAdIndex) {
return Container(
height: 72.0,
alignment: Alignment.center,
child: AdWidget(ad: _ad!),
);
} else {
// TODO: Get adjusted item index from _getDestinationItemIndex()
final item = widget.entries[_getDestinationItemIndex(index)];
return ListTile(
...
);
}
},
),
);
}
- Giải phóng tài nguyên được liên kết với đối tượng
NativeAdbằng cách gọi phương thứcNativeAd.dispose()trong phương thức gọi lạidispose().
native_inline_page.dart
@override
void dispose() {
// TODO: Dispose a NativeAd object
_ad?.dispose();
super.dispose();
}
Vậy là xong! Chạy dự án rồi nhấp vào nút Quảng cáo cùng dòng gốc trên trang chủ. Sau khi tải một quảng cáo, bạn sẽ thấy một quảng cáo gốc ở giữa danh sách.

9. Đã xong!
Bạn đã hoàn tất lớp học lập trình này. Bạn có thể tìm thấy mã hoàn chỉnh cho lớp học lập trình này trong thư mục
complete hoặc
complete_kotlin_swift.

