Table of Contents
There are several ways to earn money as a mobile developer, such as selling Flutter templates, freelancing, teaching, and monetizing your apps with admob ads which is the topic of this article. Previously we have done the Restaurant Flutter App UI Design, and we improved its user experience by Creating a Shimmer Loading Effect.
In this article, we will learn how to integrate AdMob ads in that template. You can find the source code here to follow up with the tutorial.
So without any delay, let’s cut to the chase and start writing some code!
01
of 06
Install Flutter Google Ads Package
To Integrate google AdMob ads into our app we will need the Flutter Google ads package which you can find here.
Once you open the Flutter app in your favorite IDE, run in the terminal the command:
flutter pub add google_mobile_ads
02
of 06
Create the Necessary Folders and Files
After the installation of the necessary files and classes, create a new folder inside the lib folder called controllers.
inside the controllers folder create a file called ad_manager.dart.
create another folder called data, and inside it create a file called ids.dart
03
of 06
Implement Ads
Go to android->app->main>AndroidManifest.xml
and add this meta-data
tag inside the application
tag:
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>
the android value should be your AdMob app id.
in the ids.dart file create these variables that will hold the AdMob app IDs.
//These IDs are just test IDs, replace them with you own app IDs const String bannerAdUnitIdAndroid = "ca-app-pub-3940256099942544/6300978111"; const String bannerAdUnitIos = "ca-app-pub-3940256099942544/2934735716"; const String interstitialAdUnitIdAndroid = "ca-app-pub-3940256099942544/1033173712"; const String interstitialAdUnitIdIos = "ca-app-pub-3940256099942544/4411468910";
Now in the ad_manager file import the google_admob_ads, dart:io, for the platforms, android or iOS, and the file ids.dart that hold the ids.
import 'dart:io'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import '../data/ids.dart';
and create the AdManager class that has methods for loading different types of ads( Banner, and Interstitial).
class AdManager { static Future<BannerAd> loadBannerAd(BannerAdListener listener) async { final bannerAd = BannerAd( size: AdSize.banner, adUnitId: Platform.isAndroid ? bannerAdUnitIdAndroid : bannerAdUnitIos, listener: listener, request: const AdRequest()); bannerAd.load(); return bannerAd; } static void loadInterstitialAd(Function() onAdClosed) async { InterstitialAd.load( adUnitId: Platform.isAndroid ? interstitialAdUnitIdAndroid : interstitialAdUnitIdIos, request: const AdRequest(), adLoadCallback: InterstitialAdLoadCallback( onAdLoaded: (InterstitialAd ad) { ad.fullScreenContentCallback = FullScreenContentCallback( onAdDismissedFullScreenContent: (InterstitialAd ad) { ad.dispose(); onAdClosed(); }, ); ad.show(); }, onAdFailedToLoad: (LoadAdError error) { print('InterstitialAd failed to load: $error.');}, ), ); } }
static Future<BannerAd> loadBannerAd(BannerAdListener listener) async { final bannerAd = BannerAd( size: AdSize.banner, adUnitId: Platform.isAndroid ? bannerAdUnitIdAndroid : bannerAdUnitIos, listener: listener, request: const AdRequest()); bannerAd.load(); return bannerAd; }
The first method loadBannerAd
takes BannerAdListener
and returns a Future<BannerAd>
(a Future of type BannerAd).
The BannerAd
instance is called with the following parameters:
size
: Specifies the size of the banner ad.-
adUnitId
: Specifies the ID of the ad unit to load. - The value is determined based on the platform. If the platform is Android,
bannerAdUnitIdAndroid
is used; otherwise,bannerAdUnitIos
is used. listener
: Sets the listener for the banner ad. The providedBannerAdListener
is used.request
: Creates a new instance ofAdRequest
using the const constructor. Calls theload()
method on the bannerAd instance to initiate the loading of the ad.
Finally, the method returns the bannerAd
instance as a Future
.
static void loadInterstitialAd(Function() onAdClosed) async { InterstitialAd.load( adUnitId: Platform.isAndroid ? interstitialAdUnitIdAndroid : interstitialAdUnitIdIos, request: const AdRequest(), adLoadCallback: InterstitialAdLoadCallback( onAdLoaded: (InterstitialAd ad) { ad.fullScreenContentCallback = FullScreenContentCallback( onAdDismissedFullScreenContent: (InterstitialAd ad) { ad.dispose(); onAdClosed(); }, ); ad.show(); }, onAdFailedToLoad: (LoadAdError error) { print('InterstitialAd failed to load: $error.'); }, ), ); }
The second method loadInterstitialAd
takes a function onAdClosed
as a parameter because we will navigate to the restaurant screen after closing the Ad— more on this later.
The load()
method is called on the InterstitialAd
class, with the following parameters:
adUnitId
: Specifies the ID of the ad unit to load, based on the platform. If the platform is Android,interstitialAdUnitIdAndroid
is used; otherwise,interstitialAdUnitIdIos
.-
request
: Creates a new instance ofAdRequest
using theconst
constructor. adLoadCallback
: An instanceInterstitialAdLoadCallback
is provided to handle the loading callbacks. TheInterstitialAdLoadCallback
is initialized with two callback functions:onAdLoaded
: This function is called when the interstitial ad is loaded successfully. It receives the loadedInterstitialAd
as a parameter. Inside this callback, the following steps are performed:- Assigns the
FullScreenContentCallback
to thefullScreenContentCallback
property of the loaded ad. - The
onAdDismissedFullScreenContent
callbackFullScreenContentCallback
is set to dispose the ad and invoke theonAdClosed
function. - Finally, the
show()
method is called on the loaded ad to display it.
: This function is called when the ad fails to load. TheonAdFailedToLoad
LoadAdError
object is provided as a parameter to print the error. ( avoid printing in production apps, this is only for tutorial purposes).
04
of 06
Show The Ads on Screens
Now our class is ready to use wherever screen we want. In the home screen, we create two banner ads and a bool variable to keep track of the ad’s states:
late BannerAd _firstBannerAd; late BannerAd _secondBannerAd; bool _isBannerAdLoaded = false;
In the initState()
method call loadBannerAd
from the AdManager
class passing this
as the BannerAdListener
@override void initState() { super.initState(); AdManager.loadBannerAd(this).then((ad) => setState(() { _firstBannerAd = ad; _isBannerAdLoaded = true; })); }
— Don’t forget to implement the BannerAdListener
for the current object to listen to events from the banner ad like so:
class _HomeScreenState extends State<HomeScreen> implements BannerAdListener {}
Same thing for the second banner ad:
AdManager.loadBannerAd(this).then((ad) => setState(() { _secondBannerAd = ad; _isBannerAdLoaded = true; }));
the initState()
should look something like this:
@override void initState() { super.initState(); AdManager.loadBannerAd(this).then((ad) => setState(() { _firstBannerAd = ad; _isBannerAdLoaded = true; })); AdManager.loadBannerAd(this).then((ad) => setState(() { _secondBannerAd = ad; _isBannerAdLoaded = true; })); }
You’re now all set to show the banner ad wherever on your screen. The best place I think is good on the screen to display the banner is above the recent orders horizontal ListView. and above the nearby restaurants.
![Admob Banner Ad](http://yassinebenkhay.com/wp-content/uploads/2023/07/admob-ads-flutter-548x1024.png)
First Banner:
_isBannerAdLoaded ? Center( child: SizedBox( height: _secondBannerAd.size.height.toDouble(), width: _secondBannerAd.size.width.toDouble(), child: AdWidget(ad: _secondBannerAd), ), ) : const SizedBox(),
Second Banner:
_isBannerAdLoaded ? Center( child: SizedBox( height: _firstBannerAd.size.height.toDouble(), width: _firstBannerAd.size.width.toDouble(), child: AdWidget(ad: _firstBannerAd), ), ) : const SizedBox(),
For the Interstitial Ad, when clicking any restaurant, we load the ad, then onAdClose
we display the details of that specific restaurant as follows:
GestureDetector( onTap: () { AdManager.loadInterstitialAd(() { Navigator.push( context, MaterialPageRoute( builder: (_) => RestaurantScreen(restaurant: restaurant), ), ); }); }, //Child... ),
![Interstital admob ads flutter](http://yassinebenkhay.com/wp-content/uploads/2023/07/interstitial-1024x569.jpg)
05
of 06
My Services
![](http://yassinebenkhay.com/wp-content/uploads/2023/06/yassine_bennkhay-removebg-preview.png)
Yassine: Flutter Mobile Developer.
I offer a range of services, including app development from scratch, integrating ads into your app, customization, optimization, and bug fixing.
06
of 06
Conclusion
To wrap things up, technically integrating ads into your app is a small step in the process of making money with AdMob, you should learn other things such as App Store Optimization, App Marketing, and more. All-in-all, if you want to check the full source code please refer to the GitHub repo.
Comments 1