Flutter广告展示插件tapsell_plus的使用
Flutter广告展示插件tapsell_plus的使用
Tapsell Plus 是一个中介广告SDK。通过Tapsell Plus,您可以利用多个AdNetwork为用户提供最佳的广告体验,从而增加您的广告收入。
安装
稳定版发布
稳定版本和预发布版本可以在pub上直接访问:
dependencies:
tapsell_plus: <version>
稳定版:
最新版(包括预发布):
最新变更
如果您想访问最新的功能(不一定稳定或已发布在pub),则需要从github获取包:
tapsell_plus:
git:
url: https://github.com/tapsellorg/TapsellPlusSDK-FlutterPlugin.git
使用
使用 TapsellPlus.instance.
来访问功能和方法。
初始化
void main() {
runApp(MyApp());
final appId = "TAPSELL_KEY"; // 在tapsell仪表板中获取密钥
TapsellPlus.instance.initialize(appId);
}
将
initialize
插入到main()
中是可选但推荐的。
注意:使用
TapsellPlus.instance.setDebugMode(LogLevel.Debug)
可以启用调试模式并获得详细的错误信息。
请求广告
注意:展示广告的过程是:
- 使用
zoneId
请求广告并获取responseId
- 使用
responseId
展示广告
final zoneId = "a_zoneId_for_this_type_of_ad";
// 回调方式
TapsellPlus.instance.requestInterstitialAd(zoneId).then((responseId) {
// 保存responseId -- 您需要它来展示广告
}).catchError((error) {
// 发生错误
});
// async-await方式 - 记得捕获可能的错误
final responseId = await TapsellPlus.instance.requestInsterstitialAd(zoneId);
展示广告
拥有刚刚请求的responseId
TapsellPlus.instance.showInterstitialAd(id,
onOpened: (map) {
// 广告打开 - map包含zone_id和response_id
},
onError: (map) {
// 广告展示失败 - map包含error_message, zone_id和response_id
}
);
展示广告可能会包含一个或多个
onOpened
,onClosed
,onRewarded
和onError
回调。
示例Demo
以下是一个完整的示例Demo,展示了如何使用 tapsell_plus
插件来请求和展示各种类型的广告。
import 'package:flutter/material.dart';
import 'package:tapsell_plus/tapsell_plus.dart';
import 'package:tapsell_plus/NativeAdData.dart';
import 'package:tapsell_plus/NativeAdPayload.dart';
import 'modal.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
TapsellPlus.instance.initialize(TapsellConstant.app_id);
}
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final List<Map<String, String>> _list = [];
String responseId = '';
String unitId = '';
String adNetwork = 'tapsell';
Map<String, String> zoneIds = TapsellConstant.zoneIds['Tapsell']!;
// Native Admob
String factoryId = 'FullNativeAdFactory';
bool isAdmobNativeLoaded = false;
NativeAd? admobNativeAd;
final _scaffoldKey = new GlobalKey<ScaffoldState>();
void clearLogs() => setState(() => _list.clear());
void log(String message, {String? tag}) => setState(() {
_list.add({
'tag': tag ?? 'Command',
'message': message,
'date': DateTime.now().toIso8601String()
});
});
void setResponseId(String id) => setState(() {
responseId = id;
});
void setUnitId(String id) => setState(() {
unitId = id;
});
void setAdmobNativeLoaded(bool loaded) => setState(() {
isAdmobNativeLoaded = loaded;
});
void setAdmobNativeAd(NativeAd? ad) => setState(() {
admobNativeAd = ad;
});
void updateZoneIds(int index) => setState(() {
final key = networks[index];
if (key != null && TapsellConstant.zoneIds.containsKey(key)) {
zoneIds = TapsellConstant.zoneIds[key]!;
adNetwork = key;
} else {
log('Selected index is not supported', tag: '--revise');
}
});
void showNativeAd(NativeAdData ad) => showDialog(
context: _scaffoldKey.currentContext ?? context,
builder: (context) {
return AlertDialog(
title: Text("NativeAd"),
content: NativeAdWidget(
responseId: ad.responseId ?? '',
title: ad.title ?? '',
description: ad.description ?? '',
callToAction: ad.callToActionText ?? '',
iconUrl: ad.iconUrl ?? '',
portraitImageUrl: ad.portraitImageUrl ?? '',
landScapeImageUrl: ad.landscapeImageUrl ?? '',
onClick: () => Navigator.of(context).pop()),
);
});
Map<int, String> networks = {
0: "Tapsell",
1: "Google AdMob",
2: "Chart boost",
3: "AdColony",
4: "AppLovin",
5: "Unity Ads",
};
List<Map<String, dynamic>> getActions() => [
{
'name': 'Initialize',
'desc': 'Initializes the SDK',
'ready': true,
'onClick': () {
String appId = TapsellConstant.app_id;
TapsellPlus.instance.initialize(appId);
log('Calling "initialize" with appId = $appId', tag: '--initialize');
}
},
{
'name': 'SetDebugMode',
'desc': 'Sets debug mode. Daaa!',
'ready': true,
'onClick': () {
TapsellPlus.instance.setDebugMode(LogLevel.Verbose);
log('Applying debug mode', tag: '--verbose');
}
},
{
'name': 'Set Gdpr consent',
'desc': 'Sets GDPR to true',
'ready': true,
'onClick': () {
log('Applying GDPR consent', tag: '--gdpr');
final consent = true;
TapsellPlus.instance.setGDPRConsent(consent).then((value) {
log('GDPR consent set to $consent', tag: '--gdpr-status');
}).catchError((error) {
log('Failed to apply GDPR', tag: '--gdpr-status');
});
}
},
{
'name': 'Request Interstitial Ad',
'desc': 'Title is obvious',
'ready': zoneIds["INTERSTITIAL"] != null,
'onClick': () {
String zoneId = zoneIds["INTERSTITIAL"] ?? "";
if (zoneId.isEmpty) {
log("AdNetwork '$adNetwork' does not support Interstitial", tag: '-i -n $adNetwork');
return;
}
log('Requesting for interstitial ad - ZoneId: $zoneId', tag: '--interstitial -n $adNetwork');
TapsellPlus.instance.requestInterstitialAd(zoneId).then((value) {
setResponseId(value);
log('Interstitial Ad "READY"\n responseId: $value', tag: '--interstitial -s');
}).catchError((error) {
// Error occurred
});
}
},
{
'name': 'Show Interstitial Ad',
'desc': 'Title is obvious',
'ready': zoneIds["INTERSTITIAL"] != null,
'onClick': () {
final id = responseId;
if (id.isNotEmpty) {
TapsellPlus.instance.showInterstitialAd(id,
onOpened: (map) => log('Interstitial ad opened - Data: $map', tag: '--interstitial-show'),
onError: (map) => log('Failed to show interstitial ad - $map', tag: '--interstitial-show'));
log('Showing interstitial ad', tag: '--interstitial-show');
}
}
},
{
'name': 'Request rewarded ad',
'desc': 'Title is obvious',
'ready': zoneIds["REWARDED"] != null,
'onClick': () {
String zoneId = zoneIds["REWARDED"] ?? "";
if (zoneId.isEmpty) {
log("AdNetwork '$adNetwork' does not support RewardedAd");
return;
}
log('Requesting for Rewarded. ZoneId: $zoneId', tag: '--rewarded-request -n $adNetwork');
TapsellPlus.instance.requestRewardedVideoAd(zoneId).then((value) {
log('Rewarded "READY"', tag: '--rewarded -n $adNetwork');
setResponseId(value);
});
}
},
{
'name': 'Show rewarded video ad',
'desc': 'Title is obvious',
'ready': zoneIds["REWARDED"] != null,
'onClick': () {
final id = responseId;
if (id.isNotEmpty) {
TapsellPlus.instance.showRewardedVideoAd(id, onOpened: (map) {
log('Ad opened - Data: $map', tag: '--rewarded-show');
}, onError: (map) {
log('Ad error - Error: $map', tag: '--rewarded-show');
});
}
}
},
{
'name': 'Request Standard banner',
'desc': 'Title is obvious',
'ready': zoneIds["STANDARD"] != null,
'onClick': () {
String zoneId = zoneIds["STANDARD"] ?? "";
if (zoneId.isEmpty) {
log("AdNetwork '$adNetwork' does not support StandardBanner");
return;
}
TapsellPlus.instance.requestStandardBannerAd(
zoneId, TapsellPlusBannerType.BANNER_320x50,
onResponse: (map) {
log('Standard Ad is "READY"', tag: '--standard');
setResponseId(map['response_id'] ?? '');
}, onError: (map) {
log('Standard Ad error - $map', tag: '--standard-show');
});
}
},
{
'name': 'Show Standard banner',
'desc': 'Title is obvious',
'ready': zoneIds["STANDARD"] != null,
'onClick': () {
final id = responseId;
if (id.isNotEmpty) {
TapsellPlus.instance.showStandardBannerAd(
id,
TapsellPlusHorizontalGravity.TOP,
TapsellPlusVerticalGravity.CENTER,
margin: EdgeInsets.only(top: 100), onOpened: (map) {
log('Ad opened - Data: $map', tag: '--standard-show');
}, onError: (map) {
log('Ad error - Error: $map', tag: '--standard-show');
});
}
}
},
{
'name': 'Display Standard banner',
'desc': 'Displays the banner (if hidden)',
'ready': zoneIds["STANDARD"] != null,
'onClick': () {
TapsellPlus.instance.displayStandardBanner();
}
},
{
'name': 'Hide Standard banner',
'desc': 'Note: This only changes visibility',
'ready': zoneIds["STANDARD"] != null,
'onClick': () {
TapsellPlus.instance.hideStandardBanner();
}
},
{
'name': 'Destroy Standard banner',
'desc': 'Title is obvious',
'ready': zoneIds["STANDARD"] != null,
'onClick': () {
final resId = responseId;
if (resId.isEmpty) {
log('Can not destroy while there is no responseId', tag: '--standard-destroy');
return;
}
TapsellPlus.instance.destroyStandardBanner(resId);
}
},
{
'name': 'Request Native banner',
'desc': 'Title is obvious',
'ready': zoneIds["NATIVE"] != null,
'onClick': () {
String zoneId = zoneIds["NATIVE"] ?? "";
if (zoneId.isEmpty) {
log("AdNetwork '$adNetwork' does not support NativeAd");
return;
}
TapsellPlus.instance.requestNativeAd(zoneId).then((value) {
log('Native Ad is "READY"', tag: '--native');
print('requestNativeAd:' + value.entries.toString());
setResponseId(value['response_id']);
setUnitId(value['adnetwork_zone_id'] ?? "");
}).catchError((error) {
log('Error requesting ad - $error', tag: '--native-status');
});
}
},
{
'name': 'Show Native banner',
'desc': 'Title is obvious',
'ready': zoneIds["NATIVE"] != null,
'onClick': () {
final id = responseId;
if (id.isNotEmpty) {
TapsellPlus.instance.showNativeAd(id, admobFactoryId: factoryId,
onOpened: (nativeAd) {
if (nativeAd is GeneralNativeAdPayload) {
log('Ad opened - Data: ${nativeAd.ad.toMap()}', tag: '--native-show');
showNativeAd(nativeAd.ad);
} else if (nativeAd is AdMobNativeAdPayload) {
log('Admob opened - Data: ${nativeAd.ad.responseInfo?.responseId}', tag: '--native-show');
}
}, onLoaded: (nativeAd) {
if (nativeAd is AdMobNativeAdPayload) {
setAdmobNativeLoaded(true);
} else if (nativeAd is AdMobNativeAdViewPayload) {
setAdmobNativeAd(nativeAd.nativeAdView);
}
}, onError: (map) {
log('Ad error - Error: $map', tag: '--native-show');
});
}
}
},
{
'name': 'Destroy Native banner',
'desc': 'Title is obvious',
'ready': zoneIds["NATIVE"] != null && adNetwork == 'Google AdMob',
'onClick': () {
final ad = admobNativeAd;
if (ad == null) {
log('Can not destroy while there is no ad', tag: '--native-destroy');
return;
}
admobNativeAd!.dispose();
setAdmobNativeLoaded(false);
}
},
];
}
class TapsellConstant {
static const app_id =
'alsoatsrtrotpqacegkehkaiieckldhrgsbspqtgqnbrrfccrtbdomgjtahflchkqtqosa';
static const interstitial_zone = '5cfaa942e8d17f0001ffb292';
static const rewarded_video_zone = '5cfaa802e8d17f0001ffb28e';
static const native_banner_zone = '5cfaa9deaede570001d5553a';
static const standard_zone = '5cfaaa30e8d17f0001ffb294';
static const zoneIds = {
"Tapsell": {
"REWARDED": '5cfaa802e8d17f0001ffb28e',
"INTERSTITIAL": '5cfaa942e8d17f0001ffb292',
"NATIVE": '5cfaa9deaede570001d5553a',
"STANDARD": '5cfaaa30e8d17f0001ffb294',
},
"Google AdMob": {
"REWARDED": '5cfaa8aee8d17f0001ffb28f',
"INTERSTITIAL": '5cfaa9b0e8d17f0001ffb293',
"NATIVE": '5d123c9968287d00019e1a94',
"STANDARD": '5cfaaa4ae8d17f0001ffb295',
},
"AdColony": {
"REWARDED": '5d3362766de9f600013662d5',
"INTERSTITIAL": '5d336289e985d50001427acf',
"STANDARD": '60bf4ef0d40d970001693745',
},
"AppLovin": {
"REWARDED": '5d3eb48c3aef7a0001406f84',
"INTERSTITIAL": '5d3eb4fa3aef7a0001406f85',
"STANDARD": '5d3eb5337a9b060001892441',
},
"Chart boost": {
"REWARDED": '5cfaa8cee8d17f0001ffb290',
"INTERSTITIAL": '60c5b303d756bf0001891f1c'
},
"Unity Ads": {
"REWARDED": '5cfaa8eae8d17f0001ffb291',
"INTERSTITIAL": '608d1c1c2d8e7e0001348111',
"STANDARD": '608d20a7fb661b000190bfe4',
}
};
}
更多关于Flutter广告展示插件tapsell_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter广告展示插件tapsell_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用tapsell_plus
插件来展示广告的示例代码。这个插件通常用于在Flutter应用中集成Tapsell广告服务。
首先,你需要在你的pubspec.yaml
文件中添加tapsell_plus
依赖:
dependencies:
flutter:
sdk: flutter
tapsell_plus: ^最新版本号 # 请替换为实际的最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,你需要按照Tapsell的要求进行一些配置,比如在你的AndroidManifest.xml
和Info.plist
中添加必要的权限和配置。具体配置请参考Tapsell的官方文档。
一旦配置完成,你可以在你的Flutter代码中开始使用tapsell_plus
插件。以下是一个简单的示例:
import 'package:flutter/material.dart';
import 'package:tapsell_plus/tapsell_plus.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 TapsellPlus tapsellPlus;
@override
void initState() {
super.initState();
// 初始化TapsellPlus
tapsellPlus = TapsellPlus.init(
zoneId: '你的ZoneId', // 替换为你的ZoneId
appId: '你的AppId', // 替换为你的AppId
listener: TapsellAdListener(
onAdLoaded: () {
print('广告加载成功');
},
onAdClicked: () {
print('广告被点击');
},
onAdClosed: () {
print('广告被关闭');
},
onError: (String errorMessage) {
print('广告加载失败: $errorMessage');
},
),
);
// 加载广告
loadAd();
}
void loadAd() {
tapsellPlus.loadAd();
}
void showAd() {
if (tapsellPlus.isReady()) {
tapsellPlus.showAd();
} else {
print('广告未准备好');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tapsell Plus 广告展示示例'),
),
body: Center(
child: ElevatedButton(
onPressed: showAd,
child: Text('展示广告'),
),
),
);
}
}
在这个示例中,我们:
- 在
initState
方法中初始化了TapsellPlus
对象,并设置了广告加载、点击、关闭和错误的监听器。 - 提供了
loadAd
方法来加载广告。 - 提供了
showAd
方法来展示广告,但只有在广告准备好(即isReady
返回true
)时才会展示。 - 在界面上添加了一个按钮,当点击按钮时尝试展示广告。
请确保你已经根据Tapsell的要求在后台配置了ZoneId和AppId,并且这些值在代码中正确无误。
注意:由于插件和API可能会随时间变化,建议查阅最新的tapsell_plus
插件文档以获取最准确的信息和更新。