How To Integrate AdMob Ads in Flutter App

How To Integrate AdMob Ads in Flutter App

Note: This article was originally published on yassinebenkhay.com

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!

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

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

Implement Ads

Go to android->app->main>AndroidManifest.xml and add this meta-data tag inside the applicationtag:

   <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 provided BannerAdListener is used.

  • request: Creates a new instance of AdRequest using the const constructor. Calls the load() 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 InterstitialAdclass, with the following parameters:

  • adUnitId: Specifies the ID of the ad unit to load, based on the platform. If the platform is Android, interstitialAdUnitIdAndroidis used; otherwise, interstitialAdUnitIdIos.

  • request: Creates a new instance of AdRequest using the const constructor.

  • adLoadCallback: An instance InterstitialAdLoadCallbackis provided to handle the loading callbacks. The InterstitialAdLoadCallbackis initialized with two callback functions:

  • onAdLoaded: This function is called when the interstitial ad is loaded successfully. It receives the loaded InterstitialAdas a parameter. Inside this callback, the following steps are performed:

  • Assigns the FullScreenContentCallback to the fullScreenContentCallback property of the loaded ad.

  • The onAdDismissedFullScreenContentcallback FullScreenContentCallback is set to dispose the ad and invoke the onAdClosed function.

  • Finally, the show() method is called on the loaded ad to display it.

  • onAdFailedToLoad: This function is called when the ad fails to load. The LoadAdError object is provided as a parameter to print the error. ( avoid printing in production apps, this is only for tutorial purposes).

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 loadBannerAdfrom the AdManagerclass passing thisas 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

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

My Services

I offer a range of services, including app development from scratch, integrating ads into your app, customization, optimization, and bug fixing.

Check My Services on Fiverr

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.

Did you find this article valuable?

Support Yassine BENNKHAY by becoming a sponsor. Any amount is appreciated!