showAdIfAvailable method
Shows the ad, if one exists and is not already being shown.
If the previously cached ad has expired, this just loads and caches a new ad.
Implementation
void showAdIfAvailable({VoidCallback? onComplete}) {
if (skipNextAppOpen) {
skipNextAppOpen = false;
if (kDebugMode) {
print('Skipping AppOpenAd display because skipNextAppOpen is set.');
}
onComplete?.call();
return;
}
if (!isAdAvailable) {
if (kDebugMode) {
print('Tried to show ad before available.');
}
loadAd();
onComplete?.call();
return;
}
if (_isShowingAd) {
if (kDebugMode) {
print('Tried to show ad while already showing an ad.');
}
onComplete?.call();
return;
}
if (_appOpenLoadTime != null &&
DateTime.now().subtract(maxCacheDuration).isAfter(_appOpenLoadTime!)) {
if (kDebugMode) {
print('Maximum cache duration exceeded. Loading another ad.');
}
_appOpenAd!.dispose();
_appOpenAd = null;
loadAd();
onComplete?.call();
return;
}
// Set the fullScreenContentCallback and show the ad.
_appOpenAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (ad) {
_isShowingAd = true;
skipNextAppOpen = true;
if (kDebugMode) {
print('$ad onAdShowedFullScreenContent');
}
},
onAdFailedToShowFullScreenContent: (ad, error) {
if (kDebugMode) {
print('$ad onAdFailedToShowFullScreenContent: $error');
}
_isShowingAd = false;
ad.dispose();
_appOpenAd = null;
onComplete?.call();
},
onAdDismissedFullScreenContent: (ad) {
if (kDebugMode) {
print('$ad onAdDismissedFullScreenContent');
}
_isShowingAd = false;
skipNextAppOpen = true;
ad.dispose();
_appOpenAd = null;
loadAd();
onComplete?.call();
},
);
_appOpenAd!.show();
}