diff --git a/Frontend/lib/mih_components/mih_package_components/mih_banner_ad.dart b/Frontend/lib/mih_components/mih_package_components/mih_banner_ad.dart new file mode 100644 index 00000000..95a43efb --- /dev/null +++ b/Frontend/lib/mih_components/mih_package_components/mih_banner_ad.dart @@ -0,0 +1,67 @@ +import 'package:flutter/material.dart'; +import 'package:google_mobile_ads/google_mobile_ads.dart'; +import 'package:mzansi_innovation_hub/mih_config/mih_env.dart'; + +class MihBannerAd extends StatefulWidget { + const MihBannerAd({super.key}); + + @override + State createState() => _MihBannerAdState(); +} + +class _MihBannerAdState extends State { + BannerAd? _bannerAd; + bool _isBannerAdLoaded = false; + final adUnitId = AppEnviroment.bannerAdUnitId; + + void _loadBannerAd() { + _bannerAd = BannerAd( + adUnitId: adUnitId, + request: const AdRequest(), + size: AdSize.banner, + listener: BannerAdListener( + onAdLoaded: (ad) { + debugPrint('$ad loaded.'); + setState(() { + _isBannerAdLoaded = true; + }); + }, + onAdFailedToLoad: (ad, err) { + debugPrint('BannerAd failed to load: $err'); + ad.dispose(); // Dispose the ad to free resources + }, + onAdOpened: (Ad ad) => debugPrint('$ad opened.'), + onAdClosed: (Ad ad) => debugPrint('$ad closed.'), + onAdImpression: (Ad ad) => debugPrint('$ad impression.'), + ), + ); + + _bannerAd!.load(); + } + + @override + void dispose() { + _bannerAd?.dispose(); // Dispose the ad when the widget is removed + super.dispose(); + } + + @override + void initState() { + super.initState(); + _loadBannerAd(); + } + + @override + Widget build(BuildContext context) { + return Column( + children: [ + _bannerAd != null && _isBannerAdLoaded + ? SizedBox( + width: _bannerAd!.size.width.toDouble(), + height: _bannerAd!.size.height.toDouble(), + child: AdWidget(ad: _bannerAd!)) + : SizedBox(), + ], + ); + } +}