16

I am setting ads in flutter app using firebase_admob plugin. I tried banner ad and it is working fine but, when i navigate to another page it still remains at its position. I want that ad should hide when navigating to another page.

The code snippet is as follows.

BannerAd myBanner = BannerAd(
  // Replace the testAdUnitId with an ad unit id from the AdMob dash.
  // https://developers.google.com/admob/android/test-ads
  // https://developers.google.com/admob/ios/test-ads
  adUnitId: BannerAd.testAdUnitId,
  size: AdSize.smartBanner,
  targetingInfo: targetingInfo,
  listener: (MobileAdEvent event) {
    print("BannerAd event is $event");
  },
);
myBanner
  // typically this happens well before the ad is shown
  ..load()
  ..show(
    // Positions the banner ad 60 pixels from the bottom of the screen
    anchorOffset: 60.0,
    // Banner Position
    anchorType: AnchorType.bottom,
  );
Aman gautam
  • 822
  • 2
  • 9
  • 20
  • Using [RouteObserver](https://api.flutter.dev/flutter/widgets/RouteObserver-class.html) to detect the route you want to show bannerAd is at the top or not,And now only way to hide banner is call myBanner.dispose(). – flutroid Jul 27 '19 at 22:23

5 Answers5

4

You can use RouteObserver:

class AdmobObserver extends RouteObserver<PageRoute<dynamic>> {

  BannerAd _myBanner = BannerAd(
    adUnitId: BannerAd.testAdUnitId,
    size: AdSize.smartBanner,
    listener: (MobileAdEvent event) {
      print("BannerAd event is $event");
    },
  );

  @override
  void didPush(Route route, Route previousRoute) {
    super.didPush(route, previousRoute);

    if (route.settings.name == '/') {
      // show the banner when navigating to home screen
      _showBannerAd();
    } else {
      // hide the banner when navigating to another screen
      _myBanner.dispose();
    }

  }


  @override
  void didPop(Route route, Route previousRoute) {
    super.didPop(route, previousRoute);
    if (previousRoute.settings.name == '/') {
      // show the banner again when returning back to the home screen
      _showBannerAd();
    }
  }

  void _showBannerAd() {
    _myBanner
      ..load()
      ..show(
        anchorOffset: 60.0,
        // Banner Position
        anchorType: AnchorType.bottom,
      );
  }
}

Then you need to add this observer to your MaterialApp:

  static AdmobObserver admobObserver = AdmobObserver();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: <NavigatorObserver>[admobObserver],
      .
      .
      .
Morad
  • 2,761
  • 21
  • 29
  • Thank for your answer. Working just one time (one navigation), after that i got this error everytime it lock my navigator, any idea? `Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 2416 pos 18: '!navigator._debugLocked': is not true.` – Naografix Oct 05 '20 at 23:47
  • Having the exact issue of _debugLocked. @Naografix, did you find a solution? – Elvis Ninan Jan 10 '21 at 19:45
  • This gives me new erros like 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 4506 pos 12: '!_debugLocked': is not true. – trueToastedCode Jan 25 '21 at 18:28
1

dispose() will be called when a page is destroyed. So you can distroy banner ad there.

  @override
  void dispose() {

    myBanner.dispose();

    super.dispose();
  }
Jithin Jude
  • 840
  • 14
  • 19
1

if you want to hide when show new Screen and re show when user return to last screen, you need to dispose before start new page and use async and await to await until new page pop from navigator, lets show some code

 BannerAd bannerAd;

    @override
  void initState() {
    super.initState();

    initAds();
  }   


   void openNewPage() async{
     //hide banner before start new page
     bannerAd?.dispose();
     await Navigator.push(context, MaterialPageRoute(builder: (_) => MySecondScreen()));
     //now user is return to this page so reshow banner
     initAds();
    }


    @override
  void dispose() {
    super.dispose();

    bannerAd?.dispose();
    interstitialAd?.dispose();
  }



  void initAds() async {

      bannerAd = BannerAd(
        adUnitId: kReleaseMode ? Constant.BANNER_AD_ID : BannerAd.testAdUnitId,
        size: AdSize.smartBanner,
        listener: (MobileAdEvent event) {
          print("BannerAd event is $event");
        },
      );

      bannerAd
        // typically this happens well before the ad is shown
        ..load()
        ..show(
          anchorType: AnchorType.bottom,
        );
    

  
  }

so inside this method we hide/reshow banner

void openNewPage() async{
         //hide banner before start new page
         bannerAd?.dispose();
         await Navigator.push(context, MaterialPageRoute(builder: (_) => MySecondScreen()));
         //now user is return to this page so reshow banner
         initAds();
        }
Mahmoud Abu Alheja
  • 3,343
  • 2
  • 24
  • 41
0

call Navigator.pop();

before calling Navigator.push() . This will solve your problem

RusJaI
  • 666
  • 1
  • 7
  • 28
0

Follow these steps. Consider two pages/screens as HomePage and SecondPage.

Step 1. Add this code in HomePage to go to SecondPage

myBanner?.dispose();
myBanner = null;
Navigator.push(context,
       MaterialPageRoute(builder: (context) => SecondPage()));

this will remove BannerAd object and banner will be disappeared.

Step 2. Add this code in SecondPage

Timer(Duration(seconds: 3), () {
      if(secondPageBanner == null){
        initState();
      }
    });

Put your BannerAd initialization/ Declaration code into initState() function. This will show Banner in SecondPage.

Step 3. Add this code in SecondPage when back to Homepage

secondPageBanner?.dispose();
     if(secondPageBanner != null){
         secondPageBanner = null;
       }

      setState(() {
         Navigator.pop(context);
       });

This will make secondPageBanner hidden.

Step 4. Add this code in Homepage

Timer(Duration(seconds: 3), () {
          if(myBanner == null){
            initState();
          }
        });

OR like this

void function(){
    if(myBanner == null){
         initState();
      }
}

in a button click function that button is normally clicked by user.

This will show myBanner Ad again in HomePage.