-
-
Notifications
You must be signed in to change notification settings - Fork 58
Creating a rewarded ad
Rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards.
To create a Rewarded Ad, use the class RewardedAd
:
RewardedAd rewardedAd = RewardedAd();
A single RewardedAd
object can be used to request and display ONLY ONE
rewarded ad, so you need to construct one everytime you need to show a new ad.
In order to show an ad, it needs to be loaded first. You can use load()
to load the ad:
rewardedAd.load();
Before displaying a rewarded ad to users, you must present the user with an explicit choice to view rewarded ad content in exchange for a reward. Rewarded ads must always be an opt-in experience.
To show a RewardedAd
, use the isLoaded
getter to verify that it's done loading, then call show()
. The rewarded ad from the previous code example could be shown in a button's onPressed like this:
FlatButton(
child: Text('Open rewarded ad'),
onPressed: () async {
// Load only if not loaded
(!rewardedAd.isLoaded) await rewardedAd.load();
(rewardedAd.isLoaded) rewardedAd.show();
},
),
To further customize the behavior of your ad, you can hook onto a number of events in the ad's lifecycle: loading, opening, closing, and so on. You can listen for these events using rewarded.onEvent.listen((_) {...})
:
rewardedAd.onEvent.listen((e) {
final event = e.keys.first;
switch (event) {
case RewardedAdEvent.loading:
print('loading');
break;
case RewardedAdEvent.loaded:
print('loaded');
break;
case RewardedAdEvent.loadFailed:
final errorCode = e.values.first;
print('load failed $errorCode');
break;
case RewardedAdEvent.opened:
print('ad opened');
break;
case RewardedAdEvent.closed:
print('ad closed');
break;
case RewardedAdEvent.earnedReward:
final reward = e.values.first;
print('earned reward: $reward');
break;
case RewardedAdEvent.showFailed:
final errorCode = e.values.first;
print('show failed $errorCode');
break;
default:
break;
}
});
RewardedAdEvent.closed
is a handy place to load a new interstitial after displaying the previous one:
rewardedAd.onEvent.listen((e) {
final event = e.keys.first;
switch (event) {
case RewardedAdEvent.closed:
rewardedAd = RewardedAd()..load();
break;
default:
break;
}
});
A RewardedAd
object can be used only once until it become useless, that means you need to create a new RewardedAd
everytime you need to use it again:
RewardedAd gameOverRewardedAd, extraCoinsRewardedAd;
void onPressed() async {
extraCoinsRewardedAd = RewardedAd();
await rewardedAd.load();
gameOverRewardedAd = RewardedAd();
await gameOverRewardedAd.load();
}
If you need more than one, there's gonna be too many boilerplate code. To avoid that, you can just call RewardedAd.createAndLoad()
:
void onPressed() async {
gameOverRewardedAd = await RewardedAd.createAndLoad();
// Use `..show()` if you need to show the ad as soon as it's ready
extraCoinsRewardedAd = (await RewardedAd.createAndLoad())..show();
}