@@ -67,18 +67,24 @@ class _AdLoaderWidgetState extends State<AdLoaderWidget> {
6767 /// If found, it uses the cached ad. Otherwise, it requests a new ad
6868 /// from the [AdService] and stores it in the cache upon success.
6969 Future <void > _loadAd () async {
70+ // Ensure the widget is still mounted before calling setState.
71+ // This prevents the "setState() called after dispose()" error
72+ // if the widget is removed from the tree while the async operation
73+ // is still in progress.
74+ if (! mounted) return ;
7075 setState (() {
7176 _isLoading = true ;
7277 _hasError = false ;
7378 });
74-
7579 // Attempt to retrieve the ad from the cache first.
7680 final cachedAd = _adCacheService.getAd (widget.adPlaceholder.id);
7781
7882 if (cachedAd != null ) {
7983 _logger.info (
8084 'Using cached ad for placeholder ID: ${widget .adPlaceholder .id }' ,
8185 );
86+ // Ensure the widget is still mounted before calling setState.
87+ if (! mounted) return ;
8288 setState (() {
8389 _loadedAd = cachedAd;
8490 _isLoading = false ;
@@ -105,6 +111,8 @@ class _AdLoaderWidgetState extends State<AdLoaderWidget> {
105111 );
106112 // Store the newly loaded ad in the cache.
107113 _adCacheService.setAd (widget.adPlaceholder.id, adFeedItem.nativeAd);
114+ // Ensure the widget is still mounted before calling setState.
115+ if (! mounted) return ;
108116 setState (() {
109117 _loadedAd = adFeedItem.nativeAd;
110118 _isLoading = false ;
@@ -113,6 +121,8 @@ class _AdLoaderWidgetState extends State<AdLoaderWidget> {
113121 _logger.warning (
114122 'Failed to load ad for placeholder ID: ${widget .adPlaceholder .id }. No ad returned.' ,
115123 );
124+ // Ensure the widget is still mounted before calling setState.
125+ if (! mounted) return ;
116126 setState (() {
117127 _hasError = true ;
118128 _isLoading = false ;
@@ -124,6 +134,8 @@ class _AdLoaderWidgetState extends State<AdLoaderWidget> {
124134 e,
125135 s,
126136 );
137+ // Ensure the widget is still mounted before calling setState.
138+ if (! mounted) return ;
127139 setState (() {
128140 _hasError = true ;
129141 _isLoading = false ;
0 commit comments