我是 Flutter google_mobile_ads 的新手。我已经使用 Flutter 团队的 YouTube 教程 (https://www.youtube.com/watch?v=m0d_pbgeeG8&t=1189s&ab_channel=Flutter) 实施了 Google Ads。
在本教程中,我们将 getAdListener 方法放在另一个类(Provider)中。我的问题是,如果广告无法加载,我该如何从 UI 中删除该特定广告而不是显示空白?
以下是我的视图类。
@override
void didChangeDependencies() {
super.didChangeDependencies();
_loadAds();
}
_loadAds() {
final _adState = Provider.of<AdState>(context);
_banner1 = await _adState.getBannerAd();
_banner2 = await _adState.getBannerAd();
}
_showAds() {
return Column(
children: [
if (_banner1 != null)
/*
problem: _banner1 never comes null even if the ad failed to load. if it fails how can I check and not show the _banner1 empty space?
*/
Container(child: AdWidget(ad: _banner1)),
if (_banner2 != null)
Container(child: AdWidget(ad: _banner2)),
]
);
}
我的 AdState(提供商)有 getBannerAd() 方法。
// This method will load the banner ad
Future<BannerAd> getBannerAd() async {
await this.initialization;
return BannerAd(
adUnitId: BannerAd.testAdUnitId,
size: AdSize.banner,
request: AdRequest(),
listener: this.bannerAdListener)
..load();
}
BannerAdListener _bannerAdListener = BannerAdListener(
onAdFailedToLoad: (Ad ad, LoadAdError error) {
ad.dispose();
// Now I will have to tell my UI that this particular ad failed to load and not show it
},);
谢谢