我正在使用 firebase_admob 在 Flutter 应用程序中设置广告插入。我尝试了横幅广告,它工作正常,但是,当我导航到另一个页面时,它仍然保持在原来的位置。我希望在导航到另一个页面时该广告应该隐藏。
代码片段如下。
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,
);
最佳答案
您可以使用 RouteObserver
:
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,
);
}
}
然后你需要把这个观察者添加到你的 MaterialApp
: static AdmobObserver admobObserver = AdmobObserver();
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorObservers: <NavigatorObserver>[admobObserver],
.
.
.
关于flutter - 导航到下一页时如何隐藏横幅广告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57126905/