• Home
  • Flutter
    • All
    • App Templates
    • Designs
    • Resources
    • Widgets
    Quizlet Alternative AI: Study Notes to Flashcards

    Quizlet Alternative AI: Study Notes to Flashcards

    StickerAI

    StickerAI: AI Sticker Maker for iOS

    plants selling ui design

    Plants Selling Flutter UI App Design

    7 Best Flutter Repositories on GitHub

    7 Best Flutter Repositories on GitHub

    flutter ecommerce templates

    Top 8 Ecommerce Flutter App Templates

    best-flutter-ui-kits

    10 Best Flutter UI Kits

    AI image generator app - featured image.

    Create an AI Image Generator In Flutter, Clean Architecture Part 2

    Create an ai image generator in flutter

    Create an AI Image Generator In Flutter, Clean Architecture Part 1

    How To Create a Custom AppBar In Flutter

    How To Create a Custom AppBar In Flutter

  • My Apps
  • Recommendations
  • Backend
  • How-To-Guides
  • General
No Result
View All Result
Yassine Benkhay
  • Home
  • Flutter
    • All
    • App Templates
    • Designs
    • Resources
    • Widgets
    Quizlet Alternative AI: Study Notes to Flashcards

    Quizlet Alternative AI: Study Notes to Flashcards

    StickerAI

    StickerAI: AI Sticker Maker for iOS

    plants selling ui design

    Plants Selling Flutter UI App Design

    7 Best Flutter Repositories on GitHub

    7 Best Flutter Repositories on GitHub

    flutter ecommerce templates

    Top 8 Ecommerce Flutter App Templates

    best-flutter-ui-kits

    10 Best Flutter UI Kits

    AI image generator app - featured image.

    Create an AI Image Generator In Flutter, Clean Architecture Part 2

    Create an ai image generator in flutter

    Create an AI Image Generator In Flutter, Clean Architecture Part 1

    How To Create a Custom AppBar In Flutter

    How To Create a Custom AppBar In Flutter

  • My Apps
  • Recommendations
  • Backend
  • How-To-Guides
  • General
No Result
View All Result
Yassine Benkhay
No Result
View All Result

How To Integrate AdMob Ads in Flutter App

Yassine BENKHAY by Yassine BENKHAY
July 5, 2023
in Flutter, How-To-Guides
1
admob ads
Share on FacebookShare on Twitter

Table of Contents

  • 1. Install Flutter Google Ads Package
  • 2. Create the Necessary Folders and Files
  • 3. Implement Ads
  • 4. Show The Ads on Screens
  • 5. My Services
  • 6. Conclusion

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 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).

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 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

05
of 06
My Services

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.

Check My Services on Fiverr

    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.

    Previous Post

    How to Create a Shimmer Loading Effect in Flutter

    Next Post

    How To Change AppBar Color In Flutter(2 Ways)

    Yassine BENKHAY

    Yassine BENKHAY

    Hey there, my name is Yassine. I am a bachelor degree in computer systems and software engineering, and a mobile flutter developer, refer to about me page for more information.

    Related Posts

    Quizlet Alternative AI: Study Notes to Flashcards
    Recommendations

    Quizlet Alternative AI: Study Notes to Flashcards

    by Yassine BENKHAY
    November 15, 2024
    0

    Introduction In today’s fast-paced academic environment, students need tools that adapt to their learning styles. While Quizlet has long been...

    Read more
    StickerAI

    StickerAI: AI Sticker Maker for iOS

    October 9, 2024
    plants selling ui design

    Plants Selling Flutter UI App Design

    November 28, 2023
    7 Best Flutter Repositories on GitHub

    7 Best Flutter Repositories on GitHub

    November 10, 2023
    flutter ecommerce templates

    Top 8 Ecommerce Flutter App Templates

    October 18, 2023
    best-flutter-ui-kits

    10 Best Flutter UI Kits

    October 17, 2023
    Next Post
    Change AppBar Color in Flutter

    How To Change AppBar Color In Flutter(2 Ways)

    Comments 1

    1. Pingback: Create an AI Image Generator In Flutter With Clean Architecture

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Subscribe to Our Newsletter

    Flutter Premium Templates

    Recommendations

    Quizlet Alternative AI: Study Notes to Flashcards

    November 15, 2024
    Quizlet Alternative AI: Study Notes to Flashcards

    Introduction In today’s fast-paced academic environment, students need tools that adapt to their learning styles. While Quizlet has long been...

    Read more
    by Yassine BENKHAY
    0 Comments
    Recommendations

    StickerAI: AI Sticker Maker for iOS

    October 9, 2024
    StickerAI

    Looking for a fun and simple way to create personalized stickers for your chats, social media, or even printed products?...

    Read more
    by Yassine BENKHAY
    0 Comments
    Designs

    Plants Selling Flutter UI App Design

    November 28, 2023
    plants selling ui design

    The user interface is a crucial part of any mobile application development, not only a beautiful design can shape the...

    Read more
    by Yassine BENKHAY
    0 Comments
    Yassine Benkhay

    Terms & conditions | Privacy Policy | About me | Contact
    © 2024 yassinebenkhay.com All rights reserved.

    Quick Links

    • Home
    • Flutter
    • My Apps
    • Recommendations
    • Backend
    • How-To-Guides
    • General

    Let's keep in touch!

    No Result
    View All Result
    • Home
    • Flutter
    • My Apps
    • Recommendations
    • Backend
    • How-To-Guides
    • General

    Terms & conditions | Privacy Policy | About me | Contact
    © 2024 yassinebenkhay.com All rights reserved.