createInterstitialAd method
Future<void>
createInterstitialAd(
- BuildContext context, {
- bool load = true,
- int maxLoadAttempts = 5,
- int attemptDelayFactorMs = 500,
- String? adId,
<------------------------ Load Interstitial Ad with Exponential Backoff ------------------------>
Implementation
Future<void> createInterstitialAd(
BuildContext context, {
bool load = true,
int maxLoadAttempts = 5,
int attemptDelayFactorMs = 500,
String? adId,
}) async {
final instance = AdmobEasy.instance;
final initAdID = adId ?? instance.initAdID;
if (!instance.isConnected.value || !load || initAdID.isEmpty) {
AdmobEasyLogger.error('Interstitial ad cannot load');
return;
}
// Dispose existing ad if present to prevent memory leaks
if (interstitialAd != null) {
interstitialAd!.dispose();
interstitialAd = null;
}
await InterstitialAd.load(
adUnitId: initAdID,
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (InterstitialAd ad) {
AdmobEasyLogger.success('$ad loaded');
interstitialAd = ad;
_numInterstitialLoadAttempts = 0;
interstitialAd!.setImmersiveMode(true); // Enable immersive mode
},
onAdFailedToLoad: (LoadAdError error) async {
AdmobEasyLogger.error('InterstitialAd failed to load: $error');
_numInterstitialLoadAttempts += 1;
interstitialAd = null;
// Retry with exponential backoff if attempts are less than maxLoadAttempts
if (_numInterstitialLoadAttempts < maxLoadAttempts) {
int delayMs = attemptDelayFactorMs * _numInterstitialLoadAttempts;
await Future.delayed(Duration(milliseconds: delayMs));
if (!context.mounted) return;
createInterstitialAd(
context,
load: true,
maxLoadAttempts: maxLoadAttempts,
attemptDelayFactorMs: attemptDelayFactorMs,
adId: adId,
);
} else {
_numInterstitialLoadAttempts = 0; // Reset after max attempts
}
},
),
);
}