text
stringlengths 1
372
|
|---|
to learn more about app and game monetization,
|
visit the official sites
|
of AdMob
|
and ad manager.
|
<topic_end>
|
<topic_start>
|
9. complete example
|
the following code implements a simple stateful widget that loads a
|
banner ad and shows it.
|
<code_start>
|
import 'dart:io';
|
import 'package:flutter/widgets.dart';
|
import 'package:google_mobile_ads/google_mobile_ads.dart';
|
class MyBannerAdWidget extends StatefulWidget {
|
/// the requested size of the banner. defaults to [adsize.banner].
|
final AdSize adSize;
|
/// the AdMob ad unit to show.
|
///
|
/// TODO: replace this test ad unit with your own ad unit
|
final string adUnitId = Platform.isAndroid
|
// use this ad unit on android...
|
? 'ca-app-pub-3940256099942544/6300978111'
|
// ... or this one on iOS.
|
: 'ca-app-pub-3940256099942544/2934735716';
|
MyBannerAdWidget({
|
super.key,
|
this.adSize = AdSize.banner,
|
});
|
@override
|
State<MyBannerAdWidget> createState() => _MyBannerAdWidgetState();
|
}
|
class _MyBannerAdWidgetState extends State<MyBannerAdWidget> {
|
/// the banner ad to show. this is `null` until the ad is actually loaded.
|
BannerAd? _bannerAd;
|
@override
|
widget build(BuildContext context) {
|
return SafeArea(
|
child: SizedBox(
|
width: widget.adSize.width.toDouble(),
|
height: widget.adSize.height.toDouble(),
|
child: _bannerAd == null
|
// nothing to render yet.
|
? SizedBox()
|
// the actual ad.
|
: AdWidget(ad: _bannerAd!),
|
),
|
);
|
}
|
@override
|
void initState() {
|
super.initState();
|
_loadAd();
|
}
|
@override
|
void dispose() {
|
_bannerAd?.dispose();
|
super.dispose();
|
}
|
/// loads a banner ad.
|
void _loadAd() {
|
final bannerAd = BannerAd(
|
size: widget.adSize,
|
adUnitId: widget.adUnitId,
|
request: const AdRequest(),
|
listener: BannerAdListener(
|
// called when an ad is successfully received.
|
onAdLoaded: (ad) {
|
if (!mounted) {
|
ad.dispose();
|
return;
|
}
|
setState(() {
|
_bannerAd = ad as BannerAd;
|
});
|
},
|
// called when an ad request failed.
|
onAdFailedToLoad: (ad, error) {
|
debugPrint('BannerAd failed to load: $error');
|
ad.dispose();
|
},
|
),
|
);
|
// start loading.
|
bannerAd.load();
|
}
|
}
|
<code_end>
|
lightbulb tip
|
in many cases, you will want to load the ad outside a widget.
|
for example, you can load it in a ChangeNotifier, a BLoC, a controller,
|
or whatever else you are using for app-level state. this way, you can
|
preload a banner ad in advance, and have it ready to show for when the
|
user navigates to a new screen.
|
verify that you have loaded the BannerAd instance before showing it with
|
an AdWidget, and that you dispose of the instance when it is no longer
|
needed.
|
<topic_end>
|
<topic_start>
|
add multiplayer support using firestore
|
multiplayer games need a way to synchronize game states between players.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.