Skip to content

Commit 08013eb

Browse files
committed
refactor(ads): manage native ad lifecycle with AdCacheService
- Remove premature ad disposal in AdmobNativeAdWidget - Update lifecycle management to use AdCacheService - Prevent crashes when widgets are scrolled out of view - Improve performance by caching native ads
1 parent 2bc09ee commit 08013eb

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

lib/ads/widgets/admob_native_ad_widget.dart

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,22 @@ class _AdmobNativeAdWidgetState extends State<AdmobNativeAdWidget> {
4242
void didUpdateWidget(covariant AdmobNativeAdWidget oldWidget) {
4343
super.didUpdateWidget(oldWidget);
4444
// If the nativeAd object itself has changed (e.g., a new ad was loaded
45-
// for the same placeholder ID), dispose the old ad and set the new one.
45+
// for the same placeholder ID), set the new one.
46+
// The disposal of the old ad is now handled by the AdCacheService when
47+
// the cache is cleared, preventing premature disposal of cached ads.
4648
if (widget.nativeAd.id != oldWidget.nativeAd.id) {
47-
_ad?.dispose();
4849
_setAd();
4950
}
5051
}
5152

5253
@override
5354
void dispose() {
54-
// Dispose the native ad when the widget is removed from the tree.
55-
// This is crucial for releasing native resources and preventing crashes.
56-
_ad?.dispose();
57-
_logger.info('AdmobNativeAdWidget disposed and native ad released.');
55+
// The native ad object is no longer disposed here.
56+
// Its lifecycle is managed by the AdCacheService to prevent crashes
57+
// when the widget is scrolled out of view and then back in.
58+
// The ad will be disposed when AdCacheService.clearAllAds() is called,
59+
// typically on a full feed refresh.
60+
_logger.info('AdmobNativeAdWidget disposed.');
5861
super.dispose();
5962
}
6063

0 commit comments

Comments
 (0)