I have a working code of interstitial ad with Admob in flutter, however, the ad can only be seen when the user clicks on the button. I use a timer to show the ad every 40 seconds, it prints in the console that Interstitial ad is loaded but the ad doesn't show on the device. Just want the ad to show every 40 seconds, thanks
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io' show Platform;
import 'colors.dart' as color;
import 'dart:async';
class adsinter extends StatefulWidget {
const adsinter({Key? key}) : super(key: key);
@override
_adsinterState createState() => _adsinterState();
}
Timer? _timerForInter;
class _adsinterState extends State<adsinter> {
//add Banner ad
InterstitialAd? interstitialAd;
bool isLoaded = false;
// @override
// void initState() {
// // TODO: implement initState
// // Add these lines to launch timer on start of the app
// _timerForInter = Timer.periodic(Duration(seconds: 20), (result) {
// interstitialAd;
// });
// super.initState();
// }
@override
void dispose() {
// Add these to dispose to cancel timer when user leaves the app
_timerForInter?.cancel();
interstitialAd?.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
_timerForInter = Timer.periodic(Duration(seconds: 10), (result) {
String? getBannerAdUnitId() {
String adiOS;
String adAndroid;
if (Platform.isAndroid) {
// Android-specific code
return "ca-app-pub-2014810929195140/8666570300";
} else if (Platform.isIOS) {
return "ca-app-pub-2014810929195140/7584778723";
// iOS-specific code
}
return null;
}
InterstitialAd.load(
adUnitId: getBannerAdUnitId().toString(),
//"ca-app-pub-3940256099942544/1033173712",
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (ad) {
setState(() {
isLoaded = true;
this.interstitialAd = ad;
});
print("Interstitial Ad loaded");
},
onAdFailedToLoad: (error) {
print('InterstitialAd failed to load: $error');
},
));
});
}
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(
Icons.loop,
size: 30,
color: color.AppColor.loopColor,
),
onPressed: () {
interstitialAd!.show();
},
);
}
}
this code is worked for me to show interstitial every 60sec on android
Timer? _timerForInter; // <- Put this line on top of _MyAppState class
@override
void initState() {
// Add these lines to launch timer on start of the app
_timerForInter = Timer.periodic(Duration(seconds: 60), (result) {
AdInterstitial1.loadInterstialAd();
AdInterstitial1.showInterstitialAd();
});
super.initState();
}
@override
void dispose() {
// Add these to dispose to cancel timer when user leaves the app
_timerForInter!.cancel();
super.dispose();
}