showAdIfAvailable method

void showAdIfAvailable({
  1. VoidCallback? onDismiss,
})

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? onDismiss}) {
  if (!_isEnableAd || _isLoadingAd) {
    return;
  }
  if (!isAdAvailable) {
    debugPrint('Tried to show ad before available.');
    loadAd();
    return;
  }
  if (_isShowingAd) {
    debugPrint('Tried to show ad while already showing an ad.');
    return;
  }
  if (DateTime.now().subtract(maxCacheDuration).isAfter(_appOpenLoadTime!)) {
    debugPrint('Maximum cache duration exceeded. Loading another ad.');
    _appOpenAd?.dispose();
    _appOpenAd = null;
    loadAd();
    return;
  }

  _appOpenAd?.fullScreenContentCallback = FullScreenContentCallback(
    onAdShowedFullScreenContent: (ad) {
      _isShowingAd = true;
      debugPrint('$ad onAdShowedFullScreenContent');
    },
    onAdFailedToShowFullScreenContent: (ad, error) {
      debugPrint('$ad onAdFailedToShowFullScreenContent: $error');
      _isShowingAd = false;
      ad.dispose();
      _appOpenAd = null;
    },
    onAdDismissedFullScreenContent: (ad) {
      debugPrint('$ad onAdDismissedFullScreenContent');
      _isShowingAd = false;
      ad.dispose();
      _appOpenAd = null;
      loadAd();
      onDismiss?.call();
    },
  );
  _appOpenAd?.show();
}