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();
}
});
}
Solution 1: Bostrot
If you have multiple widgets acting as individual screens you just include the part
@override void initState() {
super.initState();
myBanner ..load().then((loaded) {
if (loaded && this.mounted) {
myBanner..show();
}
});
}
You probably need to dispose it:
@override
void dispose() {
myBanner?.dispose();
super.dispose();
}
Solution 2: Oliver Atienza
I just encountered the same problem while adding Ads to my app. In my case, I was calling my method to show the banner ad in the didChangeDependencies
function. This method can be called multiple times by the app and I discovered (in my app) that it is called when you push a new route to the Navigator
that's why a call to show the banner is made as I move to other screens of my app. Maybe you have a similar implementation.
Solution 3: aknay
I found working solution from Github link here. The idea is quite simple.
- First you need an Ads helper class. You can follow the link or see below.
- Call
showBannerAd
insideinitState()
at the page that you want to show Ads. - 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();
});
- Call
hideBannderAd
insideinitState()
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;
}
}
Solution 4: Nikhil Biju
You can use await to wait for pop of second page
bannerAd.dispose();
await Navigator.pushNamed(context, f['route']);
intialzeAdd();
intialiazeAdd is called after the pop of second sceen
Solution 5: RusJ
call
Navigator.pop();
before calling Navigator.push()
. This will solve your problem