loadBannerAd method

  1. @override
Future<BannerAd?> loadBannerAd({
  1. required BuildContext? context,
  2. AdOptions? options,
  3. AdRequest? request,
})
override

获取banner广告

Implementation

@override
Future<BannerAd?> loadBannerAd({required BuildContext? context, AdOptions? options, AdRequest? request}) async {
  if (!AdsManager.isMobileAdsInitializeCalled) {
    LogUtils.w('$adsType: Mobile Ads not initialized, ad loading canceled');
    return null;
  }
  if (context == null) {
    LogUtils.w('$adsType: Context is null, ad loading canceled');
    return null;
  }
  final AdSize? adSize = options?.bannerCustomSize ?? await _getAdaptiveAdSize(context);
  if (adSize == null) {
    LogUtils.w('$adsType: Failed to determine adaptive ad size');
    return null;
  }

  final completer = Completer<BannerAd?>();
  BannerAd? bannerAd;

  void safeComplete([BannerAd? ad]) {
    if (!completer.isCompleted) {
      completer.complete(ad);
    }
  }

  void disposeAd() {
    bannerAd?.dispose();
    bannerAd = null;
  }

  bannerAd = BannerAd(
    size: adSize,
    adUnitId: adUnitId,
    request: request ?? defaultRequest,
    listener: BannerAdListener(
      onAdLoaded: (ad) {
        LogUtils.d('$adsType: Ad loaded | Size: ${adSize.width}x${adSize.height}');
        safeComplete(ad as BannerAd);
      },
      onAdFailedToLoad: (ad, error) {
        LogUtils.e('$adsType: Failed to load ad', error: error);
        disposeAd();
        safeComplete();
      },
      onPaidEvent: notifyAdRevenue,
    ),
  )..load();
  return completer.future.timeout(kLoadTimeout, onTimeout: () {
    LogUtils.w('$adsType: Load timed out after $kLoadTimeout');
    disposeAd();
    safeComplete();
    return null;
  }).catchError((error, stackTrace) {
    LogUtils.e(
      '$adsType: Unexpected loading error',
      error: error,
      stackTrace: stackTrace,
    );
    return null;
  });
}