Banner Ad not displaying on all screens when using google_mobile_ads

Viewed 276

I want to show same banner ad on all the screens of my app.
Currently it only shows on home screen where I am initializing and adding it. And when I navigate to another screen from home screen the banner ads are not showing.

Below is the code of Home_screen where I initialize the BannerAd and add it.

 @override
  void didChangeDependencies () {
    super.didChangeDependencies();
    final adState = Provider.of<AdHelper>(context);
    adState.initialization.then((status) {
      setState(() {
        banner = BannerAd(
          size: AdSize.banner,
          adUnitId: adState.bannerAdUnitId,
          listener: adState.bannerAdListener,
          request: AdRequest()
        )..load();
      });
    });
  }
  @override
  Widget build(BuildContext context) {
   return Scaffold(
    ...
    ...
    if (banner == null)
      SizedBox(
        height: 58,
      )
    else
     Container(
      height: 58,
      child: AdWidget(ad: banner),
     )

   ...
   ...

On second screen which is navigating for home screen where bannerad is not shown

 @override
  Widget build(BuildContext context) {
   return Scaffold(
    ...
    ...
    body: Column(
        children: [
          Expanded(
           ...
          ),
          SizedBox(   // Made space for bannerAd thought that bannerAd will get overlapped on this
            height: 58,
          )
   ...
   ...

I am using google_mobile_ads: ^0.13.2

2 Answers

Ads are a bit of a hassle:

  • Found it necessary to wrap Ads in a Future-builder to make them work consistently.
  • Showing Ads in web-development-environment usually failed.
  • But Ads work consistently across pages on a mobile. Especially if opening the App on a mobile without an active debugging session (reason unknown). Important to check this out.
  • Using a VPN also interferes with proper Ads display.

I cannot share production code, but the code below might point in the right direction.

Usage

Column(
  children: [
    AdService.getAdd()
  ]
)

AdService

import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

class AdService {
  static Widget getAdd() {
    const adId = 'ca-app-pub-3940256099942544/6300978111'; // Admob Dummy ID
    EdgeInsets insets = const EdgeInsets.symmetric(vertical: 10);

    return FutureBuilder<Widget>(
      future: _buildBannerWidget(adId, insets),
      builder: (_, snapshot) {
        if (!snapshot.hasData) {
          return Padding(
              padding: insets,
              child: SizedBox(
                  width: AdSize.banner.width.toDouble(),
                  height: AdSize.banner.height.toDouble(),
                  child: const Center(child: Text("Loading"))));
        }

        return snapshot.data!;
      },
    );
  }

  static Future<Widget> _buildBannerWidget(
      String adId, EdgeInsets insets) async {
    var banner = AdManagerBannerAd(
      adUnitId: adId,
      sizes: [AdSize.banner],
      request: const AdManagerAdRequest(),
      listener: _buildListener(),
    );
    await banner.dispose(); // this might not be necassary
    await banner.load();

    return Padding(
        padding: insets,
        child: SizedBox(
          width: AdSize.banner.width.toDouble(),
          height: AdSize.banner.height.toDouble(),
          child: AdWidget(ad: banner),
        ));
  }

  static AdManagerBannerAdListener _buildListener() {
    return AdManagerBannerAdListener(
      onAdOpened: (Ad ad) {
        log('BannerAdListener onAdOpened ${ad.toString()}.');
      },
      onAdClosed: (Ad ad) {
        log('BannerAdListener onAdClosed ${ad.toString()}.');
      },
      onAdImpression: (Ad ad) {
        log('BannerAdListener onAdImpression ${ad.toString()}.');
      },
      onAdWillDismissScreen: (Ad ad) {
        log('BannerAdListener onAdWillDismissScreen ${ad.toString()}.');
      },
      onPaidEvent: (
        Ad ad,
        double valueMicros,
        PrecisionType precision,
        String currencyCode,
      ) {
        log('BannerAdListener PaidEvent ${ad.toString()}.');
      },
      onAdLoaded: (Ad ad) {
        log('BannerAdListener onAdLoaded ${ad.toString()}.');
      },
      onAdFailedToLoad: (Ad bannerAd, LoadAdError error) {
        bannerAd.dispose();
        log('BannerAdListener onAdFailedToLoad error is ${error.responseInfo} | ${error.message} | ${error.code} | ${error.domain}');
      },
    );
  }
}

in your home screen create a public banner of type BannerAd

late BannerAd banner;
bool adIsLoaded = false;

@override
  void initState() {
    banner = BannerAd(
      adUnitId: //"PUT YOUR AD UNIT ID OR TEST AD UNIT iD"
      size: AdSize.banner,
      request: AdRequest(),
      listener: BannerAdListener(
        // Called when an ad is successfully received.
        onAdLoaded: (ad) {
          setState(() => adIsLoaded = true);
        },
        // Called when an ad request failed.
        onAdFailedToLoad: (ad, error) {
          setState(() => adIsLoaded = false);
          // Dispose the ad here to free resources.
          ad.dispose();
          print('Ad failed to load: $error');
        },
      ),
    );
    banner.dispose();
    banner.load();
  • on every pages (must be statfulwidget) add this lines

    void initState() {
    
          banner.dispose();
          banner.load();
          super.initState();
        }
    

create a widget like this on every page :

Widget _bannerAdWidget() {
  if (adIsLoaded) {
    return Container(
        height: banner.size.height.toDouble(),
        width: banner.size.width.toDouble(),
        child: AdWidget(
          ad: banner,
        ));
  } else
    return Container();
}

Now you can put this widget on where you want example :

return Scaffold(
      bottomNavigationBar: _bannerAdWidget(),
Related