Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Admob banner, how to show only on home

Tags:

flutter

admob

Im successfully showing the smart banner on footer and then dispose it. My problem is that is showing on all pages of the app.

My question is: How to show only on one page?

@override
 void initState() {
   super.initState();
   myBanner
   ..load().then((loaded) {
     if (loaded && this.mounted) {
       myBanner..show();
     }
   });

 }
like image 936
Alvin Konda Avatar asked Jun 21 '18 15:06

Alvin Konda


People also ask

Why are my AdMob ads not showing?

Ads won't show if you haven't integrated the Google Mobile Ads SDK correctly. Is your ad implementation code working properly? Test your implementation code to check that ads can show. You can also use ad inspector to test your app's ad serving.


1 Answers

I found working solution from Github link here. The idea is quite simple.

  1. First you need an Ads helper class. You can follow the link or see below.
  2. Call showBannerAd inside initState() at the page that you want to show Ads.
  3. Call showBannerAd like the following snippet after you pushed a page. This will show Ads again after you return back from the pushed page.
Navigator.push(context, MaterialPageRoute(builder: (context) => EditPage())).then((value) {
                      Ads.showBannerAd();
                    });
  1. Call hideBannderAd inside initState() at the pushed page that you don't want to show Ads. Then you are done.

My Ads helper class

import 'package:firebase_admob/firebase_admob.dart';

const String testDevice = 'YOUR_DEVICE_ID';

class Ads {
  static BannerAd _bannerAd;

  static void initialize() {
    FirebaseAdMob.instance.initialize(appId: FirebaseAdMob.testAppId);
  }

  static const MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
    testDevices: testDevice != null ? <String>[testDevice] : null,
    keywords: <String>['foo', 'bar'],
    contentUrl: 'http://foo.com/bar.html',
    childDirected: true,
    nonPersonalizedAds: true,
  );

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

  static void showBannerAd() {
    if (_bannerAd == null) _bannerAd = _createBannerAd();
    _bannerAd
      ..load()
      ..show(anchorOffset: 0.0, anchorType: AnchorType.bottom);
  }

  static void hideBannerAd() async {
    await _bannerAd.dispose();
    _bannerAd = null;
  }
}

like image 189
aknay Avatar answered Oct 14 '22 15:10

aknay