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(ResponseInterstitialRewarded(
        StatusInterstitialRewarded.notLoadedOnWeb));
    _log('Ads not available on the web, early abort');
  } else {
    _completer = Completer<ResponseInterstitialRewarded>();
    _adToShow = null;
    _rewardItem = null;

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

    RewardedInterstitialAd.load(
      adUnitId: _adUnitId,
      request: const AdRequest(),
      rewardedInterstitialAdLoadCallback: RewardedInterstitialAdLoadCallback(
        onAdLoaded: (ad) {
          _adToShow = ad;
          _isLoading = false;
          _log('Ad loaded');

          ad.fullScreenContentCallback =
              FullScreenContentCallback(onAdShowedFullScreenContent: (ad) {
            _log('  - onAdShowedFullScreenContent');
          }, onAdImpression: (ad) {
            _log('  - onAdImpression');
          }, onAdFailedToShowFullScreenContent: (ad, err) {
            ad.dispose();
            _log(
                '  - onAdFailedToShowFullScreenContent, completing: displayFailedUnspecificReasons');

            _completer.complete(ResponseInterstitialRewarded(
                StatusInterstitialRewarded.displayFailedUnspecificReasons));
          }, onAdDismissedFullScreenContent: (ad) {
            ad.dispose();
            if (_rewardItem != null) {
              _log(
                  '  - onAdDismissedFullScreenContent, completing: displaySuccess');
              _completer.complete(ResponseInterstitialRewarded(
                StatusInterstitialRewarded.displaySuccess,
                rewardAmount: _rewardItem!.amount,
                rewardType: _rewardItem!.type,
              ));
            } else {
              _log(
                  '  - onAdDismissedFullScreenContent, completing: displayAbortedByUser');
              _completer.complete(ResponseInterstitialRewarded(
                  StatusInterstitialRewarded.displayAbortedByUser));
            }
          }, onAdClicked: (ad) {
            _log('  - onAdClicked');
          });
        },
        onAdFailedToLoad: (LoadAdError error) {
          _isLoading = false;
          _log(
              '  - Failed to load: ${error.code} ${error.message}, completing: notLoadedGenerally');
          _completer.complete(ResponseInterstitialRewarded(
              StatusInterstitialRewarded.notLoadedGenerally,
              admobErrorCode: error.code,
              admobErrorMessage: error.message));
        },
      ),
    );
  }
}