I'm currently trying to display an admob banner in my app, However there are two pages where I would not like the banner displayed (For now i'm testing with just the settings route), And calling dispose on the banner does not hide it.
What I tried:
onDispose
methodinit
of the page I don't want the banner shown on.So far none of these approaches have been successful :( What am I doing wrong? Am I missing something?
Observer class:
class AdmobObserver extends RouteObserver<PageRoute<dynamic>> {
static ValueNotifier<bool> isBannerAdShowing = ValueNotifier<bool>(false);
BannerAd _myBanner = BannerAd(
adUnitId: AdManager.bannerAdUnitId,
size: AdSize.banner,
listener: (MobileAdEvent event) {
if (event == MobileAdEvent.loaded) {
isBannerAdShowing.value = true;
}
else if (event == MobileAdEvent.failedToLoad) {
isBannerAdShowing.value = false;
}
},
);
@override
void didPush(Route route, Route previousRoute) {
super.didPush(route, previousRoute);
if (route.settings.name == '/settings') {
_myBanner?.dispose();
isBannerAdShowing.value = false;
} else {
_showBannerAd();
}
}
@override
void didPop(Route route, Route previousRoute) {
super.didPop(route, previousRoute);
if (route.settings.name == '/settings') {
_myBanner?.dispose();
isBannerAdShowing.value = false;
} else {
_showBannerAd();
}
}
void _showBannerAd() {
_myBanner
..load()
..show();
}
}
EDIT: I managed to get the observer to call dispose but now the banner either doesn't dispose or throws an exception: This exception occurs when I navigate from Home -> Settings -> Back to home (When the app is first built the banner disappears when I go to settings, but the error still occurs, but afterwards when I hot restart the same error occurs and the banner is still there, same error also happens when I pop into settings from a different page (Settings -> Page -> pop back to Settings)
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: 'package:firebase_admob/firebase_admob.dart': Failed assertion: line 249 pos 12: '_allAds[id] != null': is not true.
E/flutter (17108): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
E/flutter (17108): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
E/flutter (17108): #2 MobileAd.dispose (package:firebase_admob/firebase_admob.dart:249:12)
E/flutter (17108): #3 AdmobObserver.didPop (package:Switcheroo/AdManager.dart:87:18)
You need to dispose the banner like this
try {
_myBanner?.dispose();
_myBanner = null;
} catch (ex) {
log("banner dispose error");
}
See here too, and the solution with the listener
property on BannerAd
. I still seem to need the catch
block for the irritating error. Although at least this way the banner hides correctly.
https://github.com/flutter/flutter/issues/21474
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With