Skip to content

Commit 40f20f9

Browse files
committed
fix a crash
1 parent ccd0b38 commit 40f20f9

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

packages/google_mobile_ads/example/lib/multi_adaptive_inline_with_recycle_example.dart

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ class _MultiInlineAdaptiveWithRecycleExampleState extends State<MultiInlineAdapt
2323
final Map<BannerAd, int> _bannerPositions = {};
2424

2525
BannerAd _createBannerAd() {
26+
print("Create a banner ad");
2627
final String bannerId = Platform.isAndroid
2728
? 'ca-app-pub-3940256099942544/6300978111'
2829
: 'ca-app-pub-3940256099942544/2934735716';
@@ -49,30 +50,29 @@ class _MultiInlineAdaptiveWithRecycleExampleState extends State<MultiInlineAdapt
4950
}
5051

5152
BannerAd _getRecycledBannerAd(int bannerPosition) {
52-
// If we already created a banner for this position, just reuse it.
53-
BannerAd? bannerAd = _banners.firstWhereOrNull((banner) => _bannerPositions[banner] == bannerPosition);
54-
if (bannerAd != null) {
55-
return bannerAd;
53+
// If we already created a banner for current position, just reuse it.
54+
BannerAd? currentBannerAd = _bannerPositions.entries.firstWhereOrNull((entry) => entry.value == bannerPosition)?.key;
55+
if (currentBannerAd != null) {
56+
return currentBannerAd;
5657
}
5758

58-
// If the cache is not full, create a new banner
5959
if (_banners.length < _cacheSize) {
60+
// If the cache is not full, create a new banner
6061
BannerAd bannerAd = _createBannerAd();
6162
_banners.add(bannerAd);
6263
_bannerPositions[bannerAd] = bannerPosition;
6364
return bannerAd;
64-
}
65-
66-
// Now the cache is full, we should recycle the banner (if possible).
67-
BannerAd banner = _banners[bannerPosition % _cacheSize];
68-
if (banner.isMounted) {
69-
// Create a new banner if it's not possible to recycle the banner
70-
// e.g. show 15 banners on screen, but _cacheSize is only 10.
71-
return _createBannerAd();
7265
} else {
73-
// Found a recyclable banner, mark it as being used by current banner position.
74-
_bannerPositions[banner] = bannerPosition;
75-
return banner;
66+
// If cache is full, we should recycle the banner (if possible).
67+
BannerAd bannerAd = _banners[bannerPosition % _cacheSize];
68+
if (bannerAd.isMounted) {
69+
// Create a new banner if it's not possible to recycle the banner
70+
// e.g. show 15 banners on screen, but _cacheSize is only 10.
71+
// This should be a corner case indicating _cacheSize should be increased.
72+
bannerAd = _createBannerAd();
73+
}
74+
_bannerPositions[bannerAd] = bannerPosition;
75+
return bannerAd;
7676
}
7777
}
7878

0 commit comments

Comments
 (0)