fetchAd method

void fetchAd()

Fetches an ad in the background.

Implementation

void fetchAd() {
  _log('Preparing to fetch...');

  if (_isLoading == true) {
    _log('Already fetching, early abort');
  } else if (kIsWeb == true) {
    _completer.complete(ResponseBanner(StatusBanner.notLoadedOnWeb));
    _log('ads not available on the web, early abort');
  } else {
    _completer = Completer<ResponseBanner>();

    _log('Fetching ...');
    _isLoading = true;

    // no await
    BannerAd(
      adUnitId: _adUnitId,
      size: AdSize.banner,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          _isLoading = false;
          _completer.complete(
              ResponseBanner(StatusBanner.loadedSuccess, ad: ad as BannerAd));
          _log('Loaded, completing: loadedSuccess');
        },
        onAdFailedToLoad: (ad, error) {
          _isLoading = false;
          ad.dispose();

          _completer.complete(ResponseBanner(StatusBanner.notLoadedGenerally,
              admobErrorCode: error.code, admobErrorMessage: error.message));
          _log(
              'Failed to load: ${error.code} ${error.message}, completing: notLoadedGenerally');
        },
      ),
    ).load();
  }
}