flutterdartadmob

Show Admob Banners without errors


I have a error with Admob banner in Flutter.

This is my error.

I/flutter (25842): AdWidget requires Ad.load to be called before AdWidget is inserted into the tree

And this is my code about Admob banner

class GoogleAdMob {
  static BannerAd loadBannerAd() {
    BannerAd banner = BannerAd(
      adUnitId: globals.admobAdUnitIdBanner!,
      size: AdSize.banner,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (
          Ad ad,
        ) =>
        onAdFailedToLoad: (
          Ad ad,
          LoadAdError error,
        ) {
          ad.dispose();
        onAdOpened: (
          Ad ad,
        ) =>
        onAdClosed: (
          Ad ad,
        ) =>
        onAdImpression: (
          Ad ad,
        ) =>
      ),
    );
    return banner;
  }

  static Container showBannerAd(
    BannerAd banner,
  ) {
    final Container adContainer = Container(
      alignment: Alignment.center,
      width: banner.size.width.toDouble(),
      height: banner.size.height.toDouble(),
      child: AdWidget(
        ad: banner,
      ),
    );

    return adContainer;
  }
}

What's matter about the error?


Solution

  • the issue you are facing, is simply complaining because AdWidget must be created AFTER the BannerAd has been loaded; although currently you are just creating and returning the BannerAd without loading it. what you need to do is to call load method in order to load it successfully and then return it.

    so now make your loadBannerAd function async and wait on the banner.load() before returning the banner. like this:

      static Future<BannerAd> loadBannerAd() async {
        final BannerAd banner = BannerAd(
    .
    .
         rest of your code ...
    .
    .
         await banner.load(); // here you need to wait for the banner to load successfully
         return banner;
    }