Could not hide ad immediately after displaying ad on flutter

Viewed 633

We have created the following class to display AdMob on flutter.

import 'package:firebase_admob/firebase_admob.dart';
import 'package:xxxxx/models/const.dart';

class Ads {
  static BannerAd _bannerAd;

  static init() {
    FirebaseAdMob.instance.initialize(appId: Const.adAppId);
  }

  static BannerAd createBannerAd() {
    return new BannerAd(
      adUnitId: Const.adUnitId,
      size: AdSize.banner,
      targetingInfo: targetingInfo,
      listener: (MobileAdEvent event) {
        print("BannerAd event $event");
      },
    );
  }

  static void showBanner() {
    if (_bannerAd == null) {
      _bannerAd = createBannerAd();
    }

    _bannerAd.load().then((load) {
      _bannerAd.show(anchorType: AnchorType.bottom);
    });
  }

  static void hideBanner() {
    _bannerAd?.dispose();
    _bannerAd = null;
  }

  static final MobileAdTargetingInfo targetingInfo = new MobileAdTargetingInfo(
    testDevices: Const.testDevices,
    keywords: Const.keywords,
    birthday: new DateTime.now(),
    gender: MobileAdGender.female,
  );
}

The following values are correctly defined in the Const class.

adAppId, adUnitId, testDevices, keywords

init() is called immediately after startup. showBanner() will be called when showing the ad. hideBanner() will be called when hiding the ad.

These will work as expected in most cases.

But after _bannerAd.show() is called, the ad will not be hidden if hideBanner() is called before the listener receives MobileAdEvent.loaded.

[OK] _bannerAd.show() -> receive MobileAdEvent.loaded -> hideBanner()

[NG] _bannerAd.show() -> hideBanner() -> (receive MobileAdEvent.loaded)

How can we avoid this if we do?

0 Answers
Related