showInterstitialAd method

void showInterstitialAd(
  1. BuildContext context, {
  2. void onAdShowedFullScreenContent(
    1. InterstitialAd
    )?,
  3. void onAdDismissedFullScreenContent(
    1. InterstitialAd
    )?,
  4. void onAdFailedToShowFullScreenContent(
    1. InterstitialAd,
    2. AdError
    )?,
})

<------------------------ Show Interstitial Ad ------------------------>

Implementation

void showInterstitialAd(
  BuildContext context, {
  void Function(InterstitialAd)? onAdShowedFullScreenContent,
  void Function(InterstitialAd)? onAdDismissedFullScreenContent,
  void Function(InterstitialAd, AdError)? onAdFailedToShowFullScreenContent,
}) {
  // Check if the interstitial ad is loaded
  if (interstitialAd == null) {
    AdmobEasyLogger.info('Interstitial ad not loaded, attempting to load...');
    if (!context.mounted) return;
    createInterstitialAd(context); // Load ad if not already loaded
    return;
  }

  // Set callbacks for full-screen content events and show the interstitial ad
  interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
    onAdShowedFullScreenContent: (InterstitialAd ad) {
      if (onAdShowedFullScreenContent != null) {
        onAdShowedFullScreenContent(ad);
      }
      AdmobEasyLogger.success('Interstitial ad displayed.');
    },
    onAdDismissedFullScreenContent: (InterstitialAd ad) {
      if (onAdDismissedFullScreenContent != null) {
        onAdDismissedFullScreenContent(ad);
      }
      AdmobEasyLogger.info('$ad dismissed.');
      interstitialAd = null; // Clear the reference to the ad
      ad.dispose(); // Dispose the ad object to free resources

      if (context.mounted) {
        createInterstitialAd(context); // Preload the next ad after dismissal
      }
    },
    onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
      if (onAdFailedToShowFullScreenContent != null) {
        onAdFailedToShowFullScreenContent(ad, error);
      }
      AdmobEasyLogger.error('Failed to show interstitial ad: $error');
      ad.dispose();
      interstitialAd = null; // Clear the reference to the failed ad
    },
  );

  interstitialAd!.show(); // Show the interstitial ad
}