Adding AdMob to your Flutter App: Part 2
Before moving on to part 2, It is highly recommended to visit part 1 for setting up, Configuring & Initializing AdMob SDK —
Adding AdMob to your Flutter App
This blog guides you through adding an AdMob to an appmedium.com
What you’ll build :
✅How to use banner ads in a demo Flutter app
✅How to use interstitial ads in a Flutter app
✅How to use rewarded ads in a Flutter app
Contents :
Awesome Drawing Quiz
This blog will guide you through adding an AdMob banner, an interstitial ad, and a rewarded ad to an app called Awesome Drawing Quiz, a game that lets players guess the name of the drawing.
✔Important : This blog provides both starter code for this App as well as the complete project code with AdMobs.
You can find the 📂 starter code for this app without ad mobs over here —
flutter-devs/AdMobs-in-Flutter
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com
Add a Banner Ad in 4 steps !
In the previous blog we did a basic setup by adding Awesome Drawing Quiz firebase admob plugin
& initialized the admob SDK . Now we will use that setup to add it into our demo Awesome Drawing Quiz App
.
In this section, you add a banner ad at the top of the game screen, as shown —
✔STEP 1 :
Open the lib/game_route.dart
file, and import ad_manager.dart
and firebase_admob.dart
by adding the following lines:
lib/game_route.dart
...
// TODO: Import ad_manager.dart
import 'package:awesome_drawing_quiz/ad_manager.dart';
// TODO: Import firebase_admob.dart
import 'package:firebase_admob/firebase_admob.dart';
class GameRoute extends StatefulWidget {
...
}
✔STEP 2 :
Next, in the _GameRouteState
class, add the following member and methods for the banner ad.
lib/game_route.dart
class _GameRouteState extends State<GameRoute> implements QuizEventListener {
...
// TODO: Add _bannerAd
BannerAd _bannerAd;
...
// TODO: Implement _loadBannerAd()
void _loadBannerAd() {
_bannerAd
..load()
..show(anchorType: AnchorType.top);
}
...
}
✔STEP 3 :
In the initState()
method, create a BannerAd
object, and load the banner ad. Note that the banner displays a 320×50 banner (AdSize.banner
).
lib/game_route.dart
@override
void initState() {
...
// TODO: Initialize _bannerAd
_bannerAd = BannerAd(
adUnitId: AdManager.bannerAdUnitId,
size: AdSize.banner,
);
// TODO: Load a Banner Ad
_loadBannerAd();
}
✔STEP 4 :
Finally, release the resource associated with the BannerAd
object by calling the BannerAd.dispose()
method in the dispose()
callback method.
lib/game_route.dart
@override
void dispose() {
// TODO: Dispose BannerAd object
_bannerAd?.dispose();
...
super.dispose();
}
That’s it! Run the project, to see a banner ad shown at the top of the game screen.
Add an Interstitial Ad in 5 steps !
✔STEP 1 :
First, add the following members and methods for the interstitial ad in the _GameRouteState
class.
lib/game_route.dart
https://gist.github.com/Anirudhk07/e04d17884fd2ecbbb619bf8ed30d4f62#file-game_route-dart
✔STEP 2 :
Next, initialize _isInterstitialAdReady
and _interstitialAd
in the initState()
method. Because _onInterstitialAdEvent
is configured as an ad event listener for _interstitialAd
, every ad event from _interstitialAd
is delivered to the _onInterstitialAdEvent
method.
lib/game_route.dart
@override
void initState() {
...
// TODO: Initialize _isInterstitialAdReady
_isInterstitialAdReady = false;
// TODO: Initialize _interstitialAd
_interstitialAd = InterstitialAd(
adUnitId: AdManager.interstitialAdUnitId,
listener: _onInterstitialAdEvent,
);
}
In this code, an interstitial ad is displayed after a user completes 5 levels. To minimize unnecessary ad requests, we start loading an ad when a user reaches level 3.
✔STEP 3:
In the onNewLevel()
method, add the following lines.
lib/game_route.dart
@override
void onNewLevel(int level, Drawing drawing, String clue) {
...
// TODO: Load an Interstitial Ad
if (level >= 3 && !_isInterstitialAdReady) {
_loadInterstitialAd();
}
}
When a game finishes, the game score dialog is displayed. When a user closes the dialog, it routes a user to the home screen of the Awesome Drawing Quiz.
Because interstitial ads should be displayed between screen transitions, we show the interstitial ad when a user clicks the CLOSE button.
✔STEP 4:
Modify the onGameOver()
method as follows:
lib/game_route.dart
https://gist.github.com/Anirudhk07/620fab75db3f29cfd3437e5c2f3b0141#file-ad-dart
✔STEP 5:
Finally, release the resource associated with the InterstitialAd
object by calling the InterstitialAd.dispose()
method in the dispose()
callback method.
lib/game_route.dart
@override
void dispose() {
...
// TODO: Dispose InterstitialAd object
_interstitialAd?.dispose();
...
super.dispose();
}
That’s it! Run the project to see an interstitial ad displayed after the game finishes.
Add a Rewarded Ad in 3 steps !
In this section, you add a rewarded ad which gives a user an additional hint as a reward.
✔STEP 1:
First, add the members and methods for the rewarded ad in the _GameRouteState
class. Note that RewardedVideoAd
is a singleton object, so you don’t need to have a member for managing the instance of the RewardedVideoAd
class.
RewardedVideoAdEvent.rewarded
is the most important ad event in a rewarded ad. It’s triggered when a user becomes eligible to receive a reward (for example., finished watching a video). In this code, RewardedVideoAdEvent.rewarded
calls the QuizManager.instance.useHint()
method which reveals one more character in the hint string.
Also, according to the ad event, RewardedVideoAdEvent.rewarded
updates the UI by changing the value of _isRewardedAdReady
. Note that _isRewardedAdReady
reloads the ad when a user closes the ad, to make sure the ad is ready as early as possible.
lib/game_route.dart
https://gist.github.com/Anirudhk07/87c1484ae0d1f08b206b3848d6d55798#file-reward-dart
✔STEP 2 :
Next, allow users to watch a rewarded ad by clicking the floating action button. The button shows only if a user hasn’t used a hint at the current level and a rewarded ad is loaded.
Modify the _buildFloatingActionButton()
method, as follows, to display the floating action button. Note that returning null
hides the button from the screen.
lib/game_route.dart
Widget _buildFloatingActionButton() {
// TODO: Return a FloatingActionButton if a Rewarded Ad is available
return (!QuizManager.instance.isHintUsed && _isRewardedAdReady)
? FloatingActionButton.extended(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Need a hint?'),
content: Text('Watch an Ad to get a hint!'),
actions: <Widget>[
FlatButton(
child: Text('cancel'.toUpperCase()),
onPressed: () {
Navigator.pop(context);
},
),
FlatButton(
child: Text('ok'.toUpperCase()),
onPressed: () {
Navigator.pop(context);
RewardedVideoAd.instance.show();
},
),
],
);
},
);
},
label: Text('Hint'),
icon: Icon(Icons.card_giftcard),
)
: null;
}
✔STEP 3:
Finally, remove the rewarded ad event listener in the dispose()
callback method.
lib/game_route.dart
@override
void dispose() {
...
// TODO: Remove Rewarded Ad event listener
RewardedVideoAd.instance.listener = null;
...
super.dispose();
}
That’s it! Run the project and watch a rewarded ad, to get an additional hint !
Congratulations ! You have now added all ads to your app ! If you missed something , you can find the completed code for this app in the 📂 complete folder.
Happy Fluttering !! ❤
Resources
firebase_admob | Flutter Package
A plugin for Flutter that supports loading and displaying banner, interstitial (full-screen), and rewarded video ads…pub.dev
flutter-devs/AdMobs-in-Flutter
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build…github.com
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.