flutter - 如何在颤振项目的一个屏幕中使用多个 Admob 横幅
问题描述
我有颤振项目,我在屏幕上添加了一个横幅广告,但我需要在同一个屏幕上加载更多,我尝试在不同的地方重复调用该函数
======== Exception caught by widgets library =======================================================
The following assertion was thrown building AdWidget(dirty, state: _AdWidgetState#72c34):
This AdWidget is already in the Widget tree
If you placed this AdWidget in a list, make sure you create a new instance in the builder function with a unique ad object.
Make sure you are not using the same ad object in more than one AdWidget.
我可以在同一个屏幕上加载多个横幅吗?
这是 Github 上的链接 https://github.com/Hussamedeen/MyDealApp
HomeScreen.dart
解决方案
由于您没有提供任何代码,我会根据我认为您可以做到的方式来假设和回答。
如果您在预定义的固定位置展示广告,则需要BannerAd
为每个位置创建一个新位置。您还必须BannerAd
像这样单独加载这些:
final BannerAd myBanner1 = BannerAd(
adUnitId: '<Banner ID>',
size: AdSize.smartBanner,
request: AdRequest(),
listener: AdListener(onAdClosed: (ad) => ad.dispose()),
);
myBanner1.load();
final adWidget1 = AdWidget(ad: myBanner1);
...
...
...
final BannerAd myBannerNth = BannerAd(
adUnitId: '<Banner ID>',
size: AdSize.banner,
request: AdRequest(),
listener: AdListener(onAdClosed: (ad) => ad.dispose()),
);
myBannerNth.load();
final adWidgetNth = AdWidget(ad: myBannerNth);
其中myBannerNth/adWidgetNth是第 n 个横幅/广告小部件。
对于动态的、自动生成的情况,例如在 a 中ListView.separated
,您可以这样做:
// Defined somewhere, e.g. in your State[less/ful] widget
Map<String, BannerAd> ads = <String, BannerAd>{};
...
...
...
ListView.separated(
separatorBuilder: (context, index) => Divider(),
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
ads['myBanner$index'] = BannerAd(
adUnitId: '<Banner ID>',
size: AdSize.banner,
request: AdRequest(),
listener: AdListener(onAdClosed: (ad) => ad.dispose()));
ads['myBanner$index'].load();
if (index % 6 == 0) {
return Column(
children: [
Container(
child: AdWidget(ad: ads['myBanner$index']),
height: 100.0,
),
_buildItem(context, items[index])
],
);
}
return _buildItem(context, items[index]);
},
itemCount: items.length,
)
ads
其值是Map
单个动态自动生成的横幅广告在哪里。