AdMob Integration 2 Flutter
AdMob can be a great way to monetize your mobile app and earn revenue while providing value to your users through relevant and targeted ads. In this article, we will see how to integrate AdMob
with a flutter application with step by step process.
Introduction:
For integrating admob with flutter we will use google_mobile_ads
package which is maintained by google.dev. Before integrating it with flutter do follow the prerequisites for android and iOS.
If facing problem while following prerequisites do let me know in the comment, and I’ll be happy to help.
Implementation:
Step 1: Add the dependencies
Add dependencies to pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
google_mobile_ads: ^2.3.0
Step 2: Import
import 'package:google_mobile_ads/google_mobile_ads.dart';
Step 3: Install the dependencies
Run the below command in the root directory of your app to install dependency.
flutter pub get
Step 4: Initialize AbMob Instance
void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
runApp(MyApp());
}
Step 5: Start with the code implementation
In this article, we will implement below three ads integration
- Banner Ads
- Rewarded Ads
- Interstitial Ads
Let’s see the implementation of each one of them in detail and understand how to create and show the ads.
- Banner Ads
- Create an ad unit ID for your banner ad. You can get this ID from your AdMob account.
static const String bannerAdUnitId = ‘your-banner-ad-unit-id’;
2. Create a BannerAd
instance for loading the ad.
BannerAd bannerAd = BannerAd(
adUnitId: bannerAdUnitId,
size: AdSize.banner,
request: const AdRequest(),
listener: BannerAdListener(
onAdLoaded: (Ad ad) => print('BannerAd loaded.'),
onAdFailedToLoad: (Ad ad, LoadAdError error) {
ad.dispose();
print('BannerAd failed to load: $error');
},
),
);
@override
void initState() {
super.initState();
bannerAd.load();
}
@override
void dispose() {
bannerAd.dispose();
super.dispose();
}
In this example, we create a BannerAd
object with the ad unit ID, size, and request. We also attach a BannerAdListener
to handle ad events, such as when the ad is loaded or fails to load.
We then load the banner ad in the initState
method and dispose of it in the dispose
method.
- Add the
AdWidget
to your widget tree to display the banner ad.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Banner Ad Example'),
),
body: Column(
children: [
Container(
height: 50,
child: AdWidget(ad: bannerAd),
),
Expanded(
child: Center(
child: Text('Your app content goes here.'),
),
),
],
),
);
}
In this example, we wrap the BannerAd
object with the AdWidget
widget and set the ad's height. We then add the AdWidget
to a container in the widget tree, along with your app's content.
Note: Don’t forget to dispose the instance which you create for any ad
- Rewarded Ads
- Create an ad unit ID for your rewarded ad. You can get this ID from your AdMob account.
static const String rewardedAdUnitId = 'your-rewarded-ad-unit-id';
2. Create a method to load RewardedAd
instance and an instance to store load attempts, which should not exceed by 3.
RewardedAd? _rewardedAd;
int _numRewardedLoadAttempts = 0;
void _createRewardedAd() {
RewardedAd.load(
adUnitId: rewardedAdUnitId,
request: const AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
print('$ad loaded.');
_rewardedAd = ad;
_numRewardedLoadAttempts = 0;
},
onAdFailedToLoad: (LoadAdError error) {
print('RewardedAd failed to load: $error');
_rewardedAd = null;
_numRewardedLoadAttempts += 1;
if (_numRewardedLoadAttempts < 3) {
_createRewardedAd();
}
},
));
}
@override
void initState() {
super.initState();
_createRewardedAd();
}
@override
void dispose() {
_rewardedAd.dispose();
super.dispose();
}
In this example, we create a RewardedAd
object with the ad unit ID and request. We also attach a RewardedAdLoadCallback
to handle ad events, such as when the ad is loaded or fails to load, and when the user earns a reward.
We then call the _createRewardedAd()
in the initState
method and dispose of it in the dispose
method.
3. Show the rewarded ad when the user triggers an action, such as clicking a button
void _showRewardedAd() {
if (_rewardedAd == null) {
print('Warning: attempt to show rewarded before loaded.');
return;
}
_rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (RewardedAd ad) =>
print('ad onAdShowedFullScreenContent.'),
onAdDismissedFullScreenContent: (RewardedAd ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose();
_createRewardedAd();
},
onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
ad.dispose();
_createRewardedAd();
},
);
_rewardedAd!.setImmersiveMode(true);
_rewardedAd!.show(
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
print('$ad with reward $RewardItem(${reward.amount}, ${reward.type})');
});
_rewardedAd = null;
}
In this example, we check if the rewarded ad is loaded using the _rewardedAd
instance. If the ad is loaded, we call the show()
method to display the ad. We also attach an onUserEarnedReward
callback to handle when the user earns a reward.
5. Add a button to your widget tree to trigger the rewarded ad
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Rewarded Ad Example'),
),
body: Center(
child: ElevatedButton(
onPressed: _showRewardedAd,
child: Text('Show Rewarded Ad'),
),
),
);
}
In this example, we add a button to the widget tree that calls the _showRewardedAd()
method when pressed.
- Interstitial Ads
- Create an ad unit ID for your interstitial ad. You can get this ID from your AdMob account.
static const String interstitialAdUnitId = 'your-interstitial-ad-unit-id';
2. Create a method to load InterstitialAd
instance and an instance to store load attempts.
InterstitialAd? _interstitialAd;
int _numInterstitialLoadAttempts = 0;
void _createInterstitialAd() {
InterstitialAd.load(
adUnitId: rewardedAdUnitId,
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (InterstitialAd ad) {
print('$ad loaded');
_interstitialAd = ad;
_numInterstitialLoadAttempts = 0;
_interstitialAd!.setImmersiveMode(true);
},
onAdFailedToLoad: (LoadAdError error) {
print('InterstitialAd failed to load: $error.');
_numInterstitialLoadAttempts += 1;
_interstitialAd = null;
if (_numInterstitialLoadAttempts < 3) {
_createInterstitialAd();
}
},
));
}
@override
void initState() {
super.initState();
_createInterstitialAd();
}
@override
void dispose() {
_interstitialAd.dispose();
super.dispose();
}
In this example, we create an InterstitialAd
object with the ad unit ID and request. We also attach an InterstitialAdLoadCallback
to handle ad events, such as when the ad is loaded, fails to load, or is closed.
We then call the _createInterstitialAd()
in the initState
method and dispose of it in the dispose
method.
3. Show the interstitial ad when the user triggers an action, such as clicking a button.
void _showInterstitialAd() {
if (_interstitialAd == null) {
print('Warning: attempt to show interstitial before loaded.');
return;
}
_interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (InterstitialAd ad) =>
print('ad onAdShowedFullScreenContent.'),
onAdDismissedFullScreenContent: (InterstitialAd ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose();
_createInterstitialAd();
},
onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
ad.dispose();
_createInterstitialAd();
},
);
_interstitialAd!.show();
_interstitialAd = null;
}
In this example, we check if the interstitial ad is not null. If it is not null, we call the fullScreenContentCallback
method to handle the full-screen content callback events, such as when the ad is shown, dismissed, or fails to show.
We then call the _showInterstitialAd()
method to display the ad and set the interstitial ad to null to prevent the user from seeing it multiple times.
4. Add a button to your widget tree to trigger the interstitial ad.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Interstitial Ad Example'),
),
body: Center(
child: ElevatedButton(
onPressed: _showInterstitialAd,
child: Text('Show Interstitial Ad'),
),
),
);
}
Full Souce Code
Here is the source code that you can clone and use for your application. Remember adding your APP-ID from AdMob account inside the AndroidManifest.xml.
GitHub Link: AdMobIntegration2Flutter
Please Follow 💙 and clap 👏, if you find the article useful. And get notified of my upcoming articles.
Follow me on Twitter: @imsnehalsingh and Github: Snehal Singh to hear about my projects.