Skip to content

Commit

Permalink
Improve ad banner
Browse files Browse the repository at this point in the history
  • Loading branch information
nilsreichardt committed Oct 12, 2024
1 parent 36cf167 commit b04734f
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions app/lib/ads/ad_banner.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import 'package:flutter/widgets.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:sharezone/ads/ads_controller.dart';

class AdBanner extends StatefulWidget {
const AdBanner({super.key});
Expand All @@ -15,14 +17,24 @@ class _AdBannerState extends State<AdBanner> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
final size =
await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
MediaQuery.sizeOf(context).width.truncate());

if (size == null) {
// Unable to get width of anchored banner.
return;
}

if (!mounted) {
return;
}

ad = BannerAd(
adUnitId: 'ca-app-pub-3940256099942544/6300978111',
request: const AdRequest(),
size: AdSize(
width: MediaQuery.of(context).size.width.toInt(),
height: 50,
),
adUnitId: context.read<AdsController>().getAdUnitId(),
request: context.read<AdsController>().createAdRequest(),
size: size,
listener: BannerAdListener(
// Called when an ad is successfully received.
onAdLoaded: (ad) {
Expand All @@ -42,9 +54,16 @@ class _AdBannerState extends State<AdBanner> {
});
}

@override
void dispose() {
ad?.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
if (_isLoaded == false) return Container();
final areAdsVisible = context.watch<AdsController>().areAdsVisible;
if (!areAdsVisible || _isLoaded == false) return Container();
return SizedBox(
height: ad!.size.height.toDouble(),
width: ad!.size.width.toDouble(),
Expand Down

0 comments on commit b04734f

Please sign in to comment.