How to hide banner ad when navigating to next page in flutter?

眉间皱痕 提交于 2020-07-05 06:24:37

问题


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,
  );

回答1:


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

  @override
  void dispose() {

    myBanner.dispose();

    super.dispose();
  }



回答2:


You can use RouteObserver. Something similar to this:

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],
      .
      .
      .


来源:https://stackoverflow.com/questions/57126905/how-to-hide-banner-ad-when-navigating-to-next-page-in-flutter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!