Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to prevent banner ad from showing if view is already disposed

I am currently experimenting with banner ads from the firebase_admob plugin. The process to show and dispose them is pretty straightforward, I do it in initState() and dispose().

The code to create and display the add looks like this:

_bannerAd = createBannerAd();
_bannerAd
  ..load().then((loaded) {
    if (loaded) {
      _bannerAd..show();
    }
  });

However, as I am calling show() asynchronously, it is possible that the view was already closed when the ad is being shown (i.e. by clicking back button really fast). In that case, the dispose() method will never be called and the ad will be "stuck" on the bottom of the screen.

How can I solve this problem? Am I using the banner ad wrong or is it possible to detect if the view was already changed? I tried using the "mounted" property of the state but it didn't seem to work.

like image 602
areiser Avatar asked Apr 14 '18 16:04

areiser


1 Answers

Just check "this.mounted" property of state class before showing the add.

    _bannerAd = createBannerAd();
    _bannerAd
  ..load().then((loaded) {
    if (loaded && this.mounted) {
      _bannerAd..show();
    }
  });
like image 153
Ganapat Avatar answered Oct 06 '22 02:10

Ganapat