loadAd method
void
loadAd({
- String? adUnitId,
- AdRequest? request,
- VoidCallback? onLoaded,
- dynamic onFailedToLoad(
- LoadAdError error
Loads a Rewarded Interstitial Ad.
Implementation
void loadAd({
String? adUnitId,
AdRequest? request,
VoidCallback? onLoaded,
Function(LoadAdError error)? onFailedToLoad,
}) {
if (!AdConstants.isPlatformSupported ||
!AdsManager.isAdsEnabled ||
_isDisposed) {
return;
}
if (_isLoading || isAdAvailable) return;
_isLoading = true;
final effectiveAdUnitId =
adUnitId ?? AdConstants.rewardedInterstitialAdUnitId;
_adUnitId = effectiveAdUnitId;
developer.log(
'Loading Rewarded Interstitial Ad (Unit: $effectiveAdUnitId)...',
name: 'RewardedInterstitialAdService',
);
RewardedInterstitialAd.load(
adUnitId: effectiveAdUnitId,
request: request ?? const AdRequest(),
rewardedInterstitialAdLoadCallback: RewardedInterstitialAdLoadCallback(
onAdLoaded: (ad) {
developer.log(
'Rewarded Interstitial Ad loaded.',
name: 'RewardedInterstitialAdService',
);
_rewardedInterstitialAd = ad;
_loadTime = DateTime.now();
_isLoading = false;
_retryAttempts = 0;
AdsManager.emitAdEvent(
AdEvent(
format: AdFormat.rewardedInterstitial,
type: AdEventType.loaded,
adUnitId: effectiveAdUnitId,
),
);
onLoaded?.call();
},
onAdFailedToLoad: (error) {
developer.log(
'Rewarded Interstitial Ad failed to load: ${error.message} (code: ${error.code})',
name: 'RewardedInterstitialAdService',
);
_rewardedInterstitialAd = null;
_loadTime = null;
_isLoading = false;
AdsManager.emitAdEvent(
AdEvent(
format: AdFormat.rewardedInterstitial,
type: AdEventType.failedToLoad,
adUnitId: effectiveAdUnitId,
loadAdError: error,
),
);
onFailedToLoad?.call(error);
if (_retryAttempts < maxRetryAttempts && !_isDisposed) {
_retryAttempts++;
final delaySeconds = 1 << _retryAttempts;
developer.log(
'Retrying Rewarded Interstitial load in $delaySeconds s (attempt $_retryAttempts)...',
name: 'RewardedInterstitialAdService',
);
_retryTimer?.cancel();
_retryTimer = Timer(
Duration(seconds: delaySeconds),
() {
if (!_isDisposed) {
loadAd(adUnitId: adUnitId, request: request);
}
},
);
}
},
),
);
}