showRewardedAd method

Future<void> showRewardedAd(
  1. BuildContext context, {
  2. void onAdShowedFullScreenContent(
    1. RewardedAd
    )?,
  3. void onAdDismissedFullScreenContent(
    1. RewardedAd
    )?,
  4. void onAdFailedToShowFullScreenContent(
    1. RewardedAd,
    2. AdError
    )?,
  5. void onUserEarnedReward(
    1. AdWithoutView,
    2. RewardItem
    )?,
})

<------------------------ Show Rewarded Ad with User Engagement Tracking ------------------------>

Implementation

Future<void> showRewardedAd(
  BuildContext context, {
  void Function(RewardedAd)? onAdShowedFullScreenContent,
  void Function(RewardedAd)? onAdDismissedFullScreenContent,
  void Function(RewardedAd, AdError)? onAdFailedToShowFullScreenContent,
  void Function(AdWithoutView, RewardItem)? onUserEarnedReward,
}) async {
  if (rewardedAd == null) {
    if (!context.mounted) return;
    AdmobEasyLogger.info("Ad not ready, attempting to load...");
    await createRewardedAd(context); // Preload before showing again
    return;
  }

  rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
    onAdShowedFullScreenContent: (RewardedAd ad) {
      if (onAdShowedFullScreenContent != null) {
        onAdShowedFullScreenContent(ad);
      }
      AdmobEasyLogger.success('Rewarded ad shown successfully.');
    },
    onAdDismissedFullScreenContent: (RewardedAd ad) {
      if (onAdDismissedFullScreenContent != null) {
        onAdDismissedFullScreenContent(ad);
      }
      ad.dispose();
      rewardedAd = null; // Set to null after disposal
      AdmobEasyLogger.info('Ad dismissed by user. Preloading the next ad...');
      if (context.mounted) {
        createRewardedAd(context); // Preload next ad after dismissal
      }
    },
    onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
      if (onAdFailedToShowFullScreenContent != null) {
        onAdFailedToShowFullScreenContent(ad, error);
      }
      ad.dispose();
      rewardedAd = null;
      AdmobEasyLogger.error('Failed to show rewarded ad: $error');
    },
  );

  await rewardedAd!.show(
    onUserEarnedReward: (adWithoutView, rewardItem) {
      AdmobEasyLogger.success(
          'User earned reward: ${rewardItem.amount} ${rewardItem.type}');
      if (onUserEarnedReward != null) {
        onUserEarnedReward(adWithoutView, rewardItem);
      }
    },
  );
}