-
Notifications
You must be signed in to change notification settings - Fork 0
/
banner_ad.dart
97 lines (85 loc) · 2.42 KB
/
banner_ad.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
class BannerAdView extends StatefulWidget {
const BannerAdView(
{super.key,
required this.androidBannerId,
required this.iOSBannerId,
required this.isTest,
required this.isShown,
required this.bannerSize});
final String androidBannerId;
final String iOSBannerId;
final bool isTest;
final bool isShown;
final AdSize bannerSize;
@override
State<StatefulWidget> createState() {
return _BannerAdViewState();
}
}
class _BannerAdViewState extends State<BannerAdView> {
BannerAd? _bannerAd;
bool _isLoaded = false;
// Initially use test ad units
String adUnitId = Platform.isAndroid
? 'ca-app-pub-3940256099942544/9214589741'
: 'ca-app-pub-3940256099942544/2435281174';
/// Loads a banner ad.
void loadAd() async {
_bannerAd = BannerAd(
adUnitId: adUnitId,
request: const AdRequest(),
size: widget.bannerSize,
listener: BannerAdListener(
// Called when an ad is successfully received.
onAdLoaded: (ad) {
debugPrint('$ad loaded.');
setState(() {
_isLoaded = true;
});
},
// Called when an ad request failed.
onAdFailedToLoad: (ad, err) {
debugPrint('BannerAd failed to load: $err');
// Dispose the ad here to free resources.
ad.dispose();
},
),
)..load();
}
@override
Widget build(BuildContext context) {
// Determine if the ad is a test, if not use real ids
if (!widget.isTest) {
if (Platform.isAndroid) {
adUnitId = widget.androidBannerId;
} else {
adUnitId = widget.iOSBannerId;
}
}
// If else, the test ad units still persist
// Make sure that the ad does not keep making requests if it doesnt have to
if (!_isLoaded) {
loadAd();
}
if (_bannerAd != null && _isLoaded && widget.isShown) {
print("Ad loaded with id $adUnitId and testing is ${widget.isTest}");
return Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
child: SizedBox(
width: _bannerAd!.size.width.toDouble(),
height: _bannerAd!.size.height.toDouble(),
child: AdWidget(ad: _bannerAd!),
),
),
);
}
return SizedBox(
height: 0,
width: 0,
);
}
}