loadInterstitialAd method

Future<void> loadInterstitialAd({
  1. VoidCallback? onLoadSuccess,
  2. dynamic onLoadFailed(
    1. String
    )?,
  3. required VoidCallback onShow,
  4. required VoidCallback onClose,
  5. required VoidCallback onClick,
})

加载插页广告 @param onLoadSuccess 广告加载成功回调,默认值为null @param onLoadFailed 广告加载失败回调,默认值为null @param onShow 广告展示回调 @param onClose 广告关闭回调 @param onClick 广告点击回调

Implementation

Future<void> loadInterstitialAd({
  VoidCallback? onLoadSuccess,
  Function(String)? onLoadFailed,
  required VoidCallback onShow,
  required VoidCallback onClose,
  required VoidCallback onClick,
}) async {
  if (_initializationStatus != AdapterInitializationState.ready) {
    onLoadFailed?.call('广告SDK未初始化');
    return;
  }

  var canRequestAds = await _authorizationManager.canRequestAds();
  if (!canRequestAds) {
    onLoadFailed?.call('用户未授权请求广告');
    return;
  }

  if (_interstitialAd != null) {
    return;
  }

  // 限制加载次数
  if (_maxInterstitialAdCount != null && _maxInterstitialAdCount! <= 0) {
    onLoadFailed?.call('插页广告加载次数已达上限');
    return;
  }

  if (_interstitialAdUnitId.isEmpty) {
    onLoadFailed?.call('插页广告单元ID为空');
    return;
  }

  InterstitialAd.load(
    adUnitId: _interstitialAdUnitId,
    request: const AdRequest(),
    adLoadCallback: InterstitialAdLoadCallback(
      // Called when an ad is successfully received.
      onAdLoaded: (ad) {
        ad.fullScreenContentCallback = FullScreenContentCallback(
          // Called when the ad showed the full screen content.
          onAdShowedFullScreenContent: (ad) {
            onShow.call();
          },
          // Called when an impression occurs on the ad.
          onAdImpression: (ad) {},
          // Called when the ad failed to show full screen content.
          onAdFailedToShowFullScreenContent: (ad, err) {
            // Dispose the ad here to free resources.
            ad.dispose();
          },
          // Called when the ad dismissed full screen content.
          onAdDismissedFullScreenContent: (ad) {
            ad.dispose();
            // 预加载广告
            _interstitialAd = null;
            onClose.call();
          },
          // Called when a click is recorded for an ad.
          onAdClicked: (ad) {
            onClick.call();
          },
        );

        onLoadSuccess?.call();
        _interstitialAd = ad;
        if (_maxInterstitialAdCount != null) {
          _maxInterstitialAdCount = _maxInterstitialAdCount! - 1;
        }
      },
      // Called when an ad request failed.
      onAdFailedToLoad: (LoadAdError error) {
        debugPrint('InterstitialAd failed to load: $error');
        onLoadFailed?.call(error.message);
      },
    ),
  );
}