createRewardedAd method
Future<void>
createRewardedAd(
- BuildContext context, {
- int maxFailedLoadAttempts = 5,
- int attemptDelayFactorMs = 500,
- String? adId,
<------------------------ Load Rewarded Ad with Exponential Backoff ------------------------>
Implementation
Future<void> createRewardedAd(
BuildContext context, {
int maxFailedLoadAttempts = 5,
int attemptDelayFactorMs = 500,
String? adId,
}) async {
final instance = AdmobEasy.instance;
final rewardedAdID = adId ?? instance.rewardedAdID;
if (!instance.isConnected.value || rewardedAdID.isEmpty) {
AdmobEasyLogger.error('Rewarded ad cannot load');
return;
}
await RewardedAd.load(
adUnitId: rewardedAdID,
request: const AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
AdmobEasyLogger.success('$ad loaded.');
rewardedAd = ad;
_numRewardedLoadAttempts = 0;
},
onAdFailedToLoad: (LoadAdError error) async {
AdmobEasyLogger.error('RewardedAd failed to load: $error');
rewardedAd = null;
_numRewardedLoadAttempts += 1;
AdmobEasyLogger.warning(
'Num Rewarded Load Attempts $_numRewardedLoadAttempts',
);
// Apply exponential backoff if failed to load
if (_numRewardedLoadAttempts < maxFailedLoadAttempts) {
int delayMs = attemptDelayFactorMs * _numRewardedLoadAttempts;
await Future.delayed(Duration(milliseconds: delayMs));
if (!context.mounted) return;
createRewardedAd(
context,
maxFailedLoadAttempts: maxFailedLoadAttempts,
attemptDelayFactorMs: attemptDelayFactorMs,
adId: adId,
);
} else {
_numRewardedLoadAttempts = 0;
}
},
),
);
}