I'm trying to show interstitial ad on every 3rd click (basically after certain number of clicks) On first 3rd click, it shows interstitial ad perfectly but after that it throws the following error
ad has not been loaded or has already been disposed.
bool _isLoaded = false;
InterstitialAd? interstitialAd;
int counter = 0;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
showInterstitialAd();
}
void showInterstitialAd(){
InterstitialAd.load(
adUnitId: "ad_id",
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
_isLoaded = true;
interstitialAd=ad;
interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (InterstitialAd ad){
print('ad dismissed');
interstitialAd!.dispose();
},
onAdFailedToShowFullScreenContent: (InterstitialAd ad, adError){
print('ad failed');
interstitialAd!.dispose();
}
);
},
onAdFailedToLoad: (error) {
interstitialAd!.dispose();
}
));
}
// show ad when counter is equal to 3
void onTap (){
if(_isLoaded && counter == 3){
interstitialAd!.show();
counter = 0;
} else {
counter ;
}
}
CodePudding user response:
Please rename your showInterstitialAd
to loadInterstitialAd
(because method only load and prepare ads) and call it after counter = 0;
Should look like this:
if(_isLoaded && counter == 3){
interstitialAd!.show();
counter = 0;
loadInterstitialAd();
} else {
counter ;
}