loadAd method
void
loadAd({
- String? adUnitId,
- AdRequest? request,
- VoidCallback? onLoaded,
- dynamic onFailedToLoad(
- LoadAdError error
Loads an 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) {
if (isAdAvailable) onLoaded?.call();
return;
}
_isLoading = true;
final effectiveAdUnitId =
adUnitId ?? _adUnitId ?? AdConstants.interstitialAdUnitId;
InterstitialAd.load(
adUnitId: effectiveAdUnitId,
request: request ?? const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
developer.log(
'Interstitial Ad loaded.',
name: 'InterstitialAdService',
);
_interstitialAd = ad;
_loadTime = DateTime.now();
_isLoading = false;
_retryAttempts = 0;
AdsManager.emitAdEvent(
AdEvent(
format: AdFormat.interstitial,
type: AdEventType.loaded,
adUnitId: effectiveAdUnitId,
),
);
onLoaded?.call();
},
onAdFailedToLoad: (error) {
developer.log(
'Interstitial Ad failed to load: ${error.message} (code: ${error.code})',
name: 'InterstitialAdService',
);
_interstitialAd = null;
_loadTime = null;
_isLoading = false;
AdsManager.emitAdEvent(
AdEvent(
format: AdFormat.interstitial,
type: AdEventType.failedToLoad,
adUnitId: effectiveAdUnitId,
loadAdError: error,
),
);
onFailedToLoad?.call(error);
if (_retryAttempts < maxRetryAttempts && !_isDisposed) {
_retryAttempts++;
final delaySeconds = 1 << _retryAttempts;
developer.log(
'Retrying Interstitial load in $delaySeconds s (attempt $_retryAttempts)...',
name: 'InterstitialAdService',
);
_retryTimer?.cancel();
_retryTimer = Timer(
Duration(seconds: delaySeconds),
() {
if (!_isDisposed) {
loadAd(adUnitId: adUnitId, request: request);
}
},
);
}
},
),
);
}