Reputation: 150
I'm using firebase_admob package in a flutter project, and when I load and show a banner ad on the first screen it's loaded and displayed correctly, but when I navigate to a new screen that doesn't contain a banner, the old banner is still shown on the new screen,
this is the creation code of the banner called in the initState()
BannerAd createBannerAd() {
return BannerAd(
adUnitId: BannerAd.testAdUnitId,
//Change BannerAd adUnitId with Admob ID
size: AdSize.smartBanner,
targetingInfo: AdsUtil.targetingInfo,
listener: (MobileAdEvent event) {
if (event == MobileAdEvent.loaded) {
// dispose after you received the loaded event seems okay.
if (mounted) {
_bannerAd..show();
setState(() {
isBannerShown = true;
});
} else {
_bannerAd = null;
setState(() {
isBannerShown = false;
});
}
} else if (event == MobileAdEvent.failedToLoad) {
_bannerAd = null;
setState(() {
isBannerShown = false;
});
}
// print("********** ********** BannerAd $event");
});
}
@override
void dispose() {
_bannerAd.dispose();
super.dispose();
}
Navigation to the second screen code :
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Navigator.of(context).pushNamed(SettingsPage.routeName);
},
),
I want to find a solution that when I navigate to a new screen the old banner get destroyed and not displayed in the new screen I navigated to.
Thanks
Upvotes: 3
Views: 1522
Reputation: 4035
When you push a new page then dispose
method is not called the native adView remains on the next screen as an overlay widget because it's not part of the widget tree. You need to keep track of pages and then load the banner and dispose it as per page change and reload the ad when the page reloads.
So instead of pushing the page, replacing it with the new page will fix the issue.
You can create RouteObserver
and keep track of the page change. Check this answer.
Upvotes: 4