Flutter儿童广告插件apsl_ads_flutter_kids的使用
Flutter儿童广告插件apsl_ads_flutter_kids的使用
请展示一些❤️给这个包,点赞👍并⭐️仓库以支持项目!
简化将各种广告网络集成到您的Flutter应用中的过程。
特性
- Google Mobile Ads(横幅广告、应用打开广告、插屏广告、激励广告、原生广告)
Admob Mediation
- 该插件提供了对AdMob中介的支持。详情。
- 简单地添加AdMob中介的本地平台设置。
平台特定设置
iOS
更新你的Info.plist
- 需要在Info.plist中添加Google Ads的关键字。
更新你的应用的ios/Runner/Info.plist
文件,添加两个键:
<key>GADApplicationIdentifier</key>
<string>YOUR_SDK_KEY</string>
- 你必须为所有由apsl-ads-flutter提供的网络添加
SKAdNetworkItems
。你可以在这里复制粘贴SKAdNetworkItems
到你的项目中。
Android
更新AndroidManifest.xml
<manifest>
<application>
<!-- 示例 AdMob 应用ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
</application>
</manifest>
初始化广告ID
import 'dart:io';
import 'ads_id_manager.dart';
class TestAdsIdManager extends AdsIdManager {
const TestAdsIdManager();
[@override](/user/override)
List<AppAdIds> get appAdIds => [
AppAdIds(
adNetwork: 'admob',
appId: Platform.isAndroid
? 'ca-app-pub-3940256099942544~3347511713'
: 'ca-app-pub-3940256099942544~1458002511',
appOpenId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/3419835294'
: 'ca-app-pub-3940256099942544/5662855259',
bannerId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/6300978111'
: 'ca-app-pub-3940256099942544/2934735716',
interstitialId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/1033173712'
: 'ca-app-pub-3940256099942544/4411468910',
rewardedId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/5224354917'
: 'ca-app-pub-3940256099942544/1712485313',
nativeId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/2247696110'
: 'ca-app-pub-3940256099942544/3986624511',
),
];
}
初始化SDK
在加载广告之前,调用ApslAds.instance.initialize()
初始化Mobile Ads SDK。这将初始化SDK并返回一个当初始化完成时(或30秒超时后)完成的Future
。这只需要做一次,最好是在运行应用之前。
import 'package:apsl_ads_flutter/apsl_ads_flutter.dart';
import 'package:flutter/material.dart';
const IAdIdManager adIdManager = TestAdIdManager();
ApslAds.instance.initialize(
adIdManager,
adMobAdRequest: const AdRequest(),
admobConfiguration: RequestConfiguration(testDeviceIds: []),
);
插屏广告/激励广告
加载广告
广告在显示时会自动加载,或者在首次调用initialize()
时加载。作为安全措施,你可以调用此方法来加载激励和插屏广告。如果广告已经加载,则不会重新加载。
ApslAds.instance.loadAd();
显示插屏广告或激励广告
ApslAds.instance.showAd(AdUnitType.rewarded);
显示应用打开广告
ApslAds.instance.showAd(AdUnitType.appOpen)
显示横幅广告
这是如何在小部件树中显示横幅广告的方式:
[@override](/user/override)
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SomeWidget(),
const Spacer(),
ApslBannerAd(
adNetwork: AdNetwork.admob,
adSize: AdSize.mediumRectangle,
),
],
);
}
依次显示所有横幅广告
横幅广告将尝试按您提供的顺序加载广告网络。如果由于任何原因某个网络无法加载,它会自动切换到下一个网络以防止收入损失。
要设置所有横幅广告的顺序,只需在ApslAllBannerAd
构造函数中传递orderOfAdNetworks
参数即可。否则,默认顺序为[admob, facebook, unity],默认广告尺寸为AdSize.banner。
这是如何在小部件树中显示横幅广告的方式:
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('我的应用'),
),
body: Column(
children: [
// 你的其他小部件...
ApslAllBannerAd(
orderOfAdNetworks: [
AdNetwork.admob,
],
adSize: AdSize.largeBanner,
// 其他参数...
),
// 你的其他小部件...
],
),
);
}
监听回调
在类中声明此对象:
StreamSubscription? _streamSubscription;
以下代码片段演示了显示插屏广告并检查是否已显示的过程:
如果为true
,我们取消最后订阅的回调。然后,我们监听流并访问所需的特定事件。
if (ApslAds.instance.showInterstitialAd()) {
// 取消最后一个订阅的回调
_streamSubscription?.cancel();
// 监听来自showInterstitialAd()的回调
_streamSubscription = ApslAds.instance.onEvent.listen((event) {
if (event.adUnitType == AdUnitType.interstitial &&
event.type == AdEventType.adDismissed) {
_streamSubscription?.cancel();
goToNextScreen(countryList[index]);
}
});
}
示例代码
以下是示例代码的完整实现:
import 'dart:async';
import 'dart:io';
import 'package:apsl_ads_flutter_kids/apsl_ads_flutter_kids.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
const AdsIdManager adIdManager = TestAdsIdManager();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await ApslAds.instance.initialize(
isShowAppOpenOnAppStateChange: true,
adIdManager,
adMobAdRequest: const AdRequest(),
admobConfiguration: RequestConfiguration(testDeviceIds: []),
showAdBadge: false,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Apsl Ads 示例',
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
[@override](/user/override)
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
/// 使用它来取消订阅的回调
StreamSubscription? _streamSubscription;
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("广告列表"),
centerTitle: true,
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
_sectionTitleWidget(context, title: '应用打开广告'),
AdListTile(
networkName: 'Admob 应用打开广告',
onTap: () => _showAd(AdNetwork.admob, AdUnitType.appOpen),
),
const ApslSequenceNativeAd(templateType: TemplateType.medium),
const Divider(thickness: 2),
_sectionTitleWidget(context, title: '插屏广告'),
AdListTile(
networkName: 'Admob 插屏广告',
onTap: () => _showAd(AdNetwork.admob, AdUnitType.interstitial),
),
AdListTile(
networkName: '显示插屏广告一个接一个',
onTap: () => _showAvailableAd(AdUnitType.interstitial),
),
const Divider(thickness: 2),
_sectionTitleWidget(context, title: '激励广告'),
AdListTile(
networkName: 'Admob 激励广告',
onTap: () => _showAd(AdNetwork.admob, AdUnitType.rewarded),
),
AdListTile(
networkName: '显示激励广告一个接一个',
onTap: () => _showAvailableAd(AdUnitType.rewarded),
),
AdListTile(
networkName: "导航广告",
onTap: () => _showAdOnNavigation(),
),
const ApslSequenceBannerAd(
orderOfAdNetworks: [
AdNetwork.admob,
],
),
],
),
),
),
);
}
Widget _sectionTitleWidget(BuildContext context, {String title = ""}) {
return ListTile(
title: Text(
title,
style: Theme.of(context)
.textTheme
.headlineSmall!
.copyWith(color: Colors.blue, fontWeight: FontWeight.bold),
),
);
}
void _showAd(AdNetwork adNetwork, AdUnitType adUnitType) {
if (ApslAds.instance.showAd(
adUnitType,
adNetwork: adNetwork,
shouldShowLoader: Platform.isAndroid,
context: context,
delayInSeconds: 1,
)) {
// 取消最后一个订阅的回调
_streamSubscription?.cancel();
// 监听来自showRewardedAd()的回调
_streamSubscription = ApslAds.instance.onEvent.listen((event) {
if (event.adUnitType == adUnitType) {
_streamSubscription?.cancel();
goToNextScreen(adNetwork: adNetwork);
}
});
} else {
goToNextScreen(adNetwork: adNetwork);
}
}
void _showAvailableAd(AdUnitType adUnitType) {
if (ApslAds.instance.showAd(adUnitType)) {
// 取消最后一个订阅的回调
_streamSubscription?.cancel();
// 监听来自showRewardedAd()的回调
_streamSubscription = ApslAds.instance.onEvent.listen((event) {
if (event.adUnitType == adUnitType) {
_streamSubscription?.cancel();
goToNextScreen();
}
});
} else {
goToNextScreen();
}
}
void _showAdOnNavigation() {
if (ApslAds.instance.showAdOnNavigation()) {
// 取消最后一个订阅的回调
_streamSubscription?.cancel();
// 监听来自showRewardedAd()的回调
_streamSubscription = ApslAds.instance.onEvent.listen((event) {
if (event.adUnitType == AdUnitType.interstitial) {
if (event.type == AdEventType.adFailedToLoad ||
event.type == AdEventType.adDismissed) {
_streamSubscription?.cancel();
goToNextScreen();
}
}
});
} else {
goToNextScreen();
}
}
void goToNextScreen({AdNetwork? adNetwork}) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(adNetwork: adNetwork),
),
);
}
}
class DetailScreen extends StatefulWidget {
final AdNetwork? adNetwork;
const DetailScreen({super.key, this.adNetwork = AdNetwork.admob});
[@override](/user/override)
State<DetailScreen> createState() => _DetailScreenState();
}
class _DetailScreenState extends State<DetailScreen> {
late final WebViewController _webViewController;
[@override](/user/override)
void initState() {
super.initState();
_webViewController = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
// 更新加载进度条。
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(
"https://support.google.com/admob/answer/9234653?hl=en#:~:text=AdMob%20is%20a%20mobile%20ad,helping%20you%20serve%20ads%20globally."));
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("ApslAds 示例")),
body: WebViewWidget(
controller: _webViewController,
),
);
}
}
class AdListTile extends StatelessWidget {
final String networkName;
final VoidCallback onTap;
const AdListTile({super.key, required this.networkName, required this.onTap});
[@override](/user/override)
Widget build(BuildContext context) {
return ListTile(
title: Text(
networkName,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w400,
color: Colors.black54,
),
),
trailing: const Icon(Icons.arrow_forward_ios),
onTap: onTap,
);
}
}
更多关于Flutter儿童广告插件apsl_ads_flutter_kids的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter儿童广告插件apsl_ads_flutter_kids的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中集成和使用apsl_ads_flutter_kids
插件的详细步骤和相关代码案例。这个插件主要用于在Flutter应用中展示儿童友好的广告。
步骤 1: 添加依赖
首先,你需要在pubspec.yaml
文件中添加apsl_ads_flutter_kids
依赖。
dependencies:
flutter:
sdk: flutter
apsl_ads_flutter_kids: ^最新版本号 # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
步骤 2: 配置Android和iOS项目
Android
- 在
android/app/src/main/AndroidManifest.xml
中添加必要的权限和配置。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<!-- 其他配置 -->
<!-- 添加网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- AdMob 应用ID(如果需要) -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx"/>
</manifest>
- 确保你的
android/app/build.gradle
文件中应用了Google Play服务和AdMob的依赖(如果需要)。
dependencies {
implementation 'com.google.android.gms:play-services-ads:20.6.0'
}
iOS
- 在
ios/Runner/Info.plist
中添加AdMob相关的配置(如果需要)。
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
- 在
ios/Podfile
中确保使用了最新的Google Mobile Ads SDK(如果需要)。
platform :ios, '10.0'
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
# 添加或更新Google Mobile Ads SDK
pod 'Google-Mobile-Ads-SDK', '~> 8.11.0'
end
然后运行pod install
。
步骤 3: 初始化并使用插件
在你的Flutter应用中,你需要初始化apsl_ads_flutter_kids
插件并展示广告。
import 'package:flutter/material.dart';
import 'package:apsl_ads_flutter_kids/apsl_ads_flutter_kids.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: AdDemoPage(),
);
}
}
class AdDemoPage extends StatefulWidget {
@override
_AdDemoPageState createState() => _AdDemoPageState();
}
class _AdDemoPageState extends State<AdDemoPage> {
late BannerAd _bannerAd;
late InterstitialAd _interstitialAd;
@override
void initState() {
super.initState();
// 初始化Banner广告
_bannerAd = BannerAd(
adUnitId: 'ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx', // 替换为你的Banner广告单元ID
size: AdSize.banner,
listener: BannerAdListener(
onAdLoaded: () {
print('Banner Ad Loaded');
},
onAdFailedToLoad: (AdError error) {
print('Banner Ad Failed to Load: ${error.message}');
},
onAdOpened: () {
print('Banner Ad Opened');
},
onAdClosed: () {
print('Banner Ad Closed');
},
onAdLeftApplication: () {
print('Banner Ad Left Application');
},
),
)..load();
// 初始化插屏广告
_interstitialAd = InterstitialAd(
adUnitId: 'ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx', // 替换为你的插屏广告单元ID
listener: InterstitialAdListener(
onAdLoaded: () {
print('Interstitial Ad Loaded');
_interstitialAd.show();
},
onAdFailedToLoad: (AdError error) {
print('Interstitial Ad Failed to Load: ${error.message}');
},
onAdOpened: () {
print('Interstitial Ad Opened');
},
onAdClosed: () {
print('Interstitial Ad Closed');
_loadInterstitialAd();
},
onAdLeftApplication: () {
print('Interstitial Ad Left Application');
},
),
);
_loadInterstitialAd();
}
void _loadInterstitialAd() {
_interstitialAd.load();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('APSL Ads Flutter Kids Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 50,
child: AdWidget(ad: _bannerAd),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_interstitialAd.isLoaded) {
_interstitialAd.show();
} else {
_loadInterstitialAd();
}
},
child: Text('Show Interstitial Ad'),
),
],
),
),
);
}
}
这个示例代码展示了如何初始化Banner广告和插屏广告,并在Flutter应用中展示它们。你需要替换adUnitId
为你的实际广告单元ID。
注意事项
- 确保你已经创建了AdMob账号并获取了广告单元ID。
- 遵守AdMob的广告政策,特别是针对儿童应用的广告政策。
- 在发布应用之前,彻底测试广告功能。
希望这些信息对你有所帮助!