How to Use Google Mobile Ads in Flutter?

Hey Everyone,

Today in this article we are going to learn about how to use “Google Mobile Ads” in flutter project.

Introduction

This article will guide you on how to add banner, interstitial and rewarded ads to the app.

Step 1: Create new flutter project.

Step 2: Add the Google Mobile Ads Flutter plugin.

Google mobile ads package is supports displaying and loading banner, interstitial, rewarded using the AdMob API. Flutter is a multi-platform SDK,      google_mobile_ads package is supporting on both Android and iOS. So, if you add a package into your Flutter project, it is usable by both Android and iOS.

Add the Google Mobile Ads plugin as a dependency For access the AdMob from the AdMob inline ads, foremost add google_mobile_ads as a dependency to the pubspec.yaml file that is located at the root of the project.

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  google_mobile_ads: ^0.13.0

Now, Click Pub get to install the package into your project or run “flutter pub get” command into your android studio terminal to install package into your project.

Step 3: Now you have to add your AdMob app ID into AndroidManifest.xml (Android).

<manifest>
    <application>
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>
    </application>
</manifest>

Step 4: Then you have to your AdMob app ID for iOS into Info.plist file (ios/Runner/Info.plist) (iOS).

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>

Step 5: Add class for ads ID.

Foremost you have to create one file name is AdHelpers.dart.

After that you have to add new class in that you have top manage your app ID of different ads, so you have to create new class and in that you have to create three static function that is helping you to used Google mobile ads ID.

import 'dart:io';

class AdHelper {

  static String get bannerAdUnitId {
    if (Platform.isAndroid) {
      return 'ca-app-pub-3940256099942544/6300978111';
    } else if (Platform.isIOS) {
      return 'ca-app-pub-3940256099942544/2934735716';
    } else {
      throw new UnsupportedError('Unsupported platform');
    }
  }

  static String get interstitialAdUnitId {
    if (Platform.isAndroid) {
      return "ca-app-pub-3940256099942544/1033173712";
    } else if (Platform.isIOS) {
      return "ca-app-pub-3940256099942544/4411468910";
    } else {
      throw new UnsupportedError("Unsupported platform");
    }
  }

  static String get rewardedAdUnitId {
    if (Platform.isAndroid) {
      return "ca-app-pub-3940256099942544/5224354917";
    } else if (Platform.isIOS) {
      return "ca-app-pub-3940256099942544/1712485313";
    } else {
      throw new UnsupportedError("Unsupported platform");
    }
  }
}

Step 6: Initialize Google_mobile_ads SDK.

Before loading ads, you need to initialize the Google Mobile Ads SDK. So you need to initialize google mobile ads before homepage loading so open main.Dart page and initialized _initGoogleMobileAds().

import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(
    MyApps(),
  );
}

class MyApp extends StatefulWidget {
  @override
  MyAppsState createState() => MyAppsState();
}

class MyAppsState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }
}

Step 7: Banner ad.

In this step you can learn about banner ads that how can you initialize that and how to load banner ads.

Follow below step for banner ads.

  • Create one file name is banner.dart.
  • In that create stateful class and initialize bellow function to load banner ads.
@override
void initState() {
  bannerAd = BannerAd(
    adUnitId: AdHelper.bannerAdUnitId,
    request: AdRequest(),
    size: AdSize.banner,
    listener: BannerAdListener(
      onAdLoaded: (_) {
        setState(() {
          isBannerAdReady = true;
        });
      },
      onAdFailedToLoad: (ad, error) {
        print('Failed to load a banner ad: ${error.message}');
        isBannerAdReady = false;
        ad.dispose();
      },
    ),
  );
  bannerAd.load();
}
  • Now create view of banner ads and display loaded ads.
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Align(
              alignment: Alignment.topCenter,
              child: Container(
                width: _bannerAd.size.width.toDouble(),
                height: _bannerAd.size.height.toDouble(),
                child: AdWidget(ad: _bannerAd),
              ),
            ),
  );
}

That’s it now restart whole application, and you can see banner ads in your project.

Step 8: Interstitial ad.

In this step you can learn about Interstitial ads that how can you initialize that and how to load Interstitial ads.

Follow below step for Interstitial ads.

  • Create one file name is interstitial.dart.
  • In that create one class name is Interstitial Ads.
  • In class create two variable.
InterstitialAd interstitialAd;
bool isInterstitialAdReady = false;
  • Now add function for load Interstitial Ads.
static loadInterstitialAd() {
    InterstitialAd.load(
      adUnitId: AdHelper.interstitialAdUnitId,
      request: AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (ad) {
          interstitialAd = ad;
          isInterstitialAdReady = true;

        },
        onAdFailedToLoad: (error) {
          print('Failed to load an interstitial ad: ${error.message}');
          isInterstitialAdReady = false;
        },
      ),
    );
  }
  • Now create one more function for show interstitial Ad.
static showAdmobInterstitial() async {
    if (admobInterstitial != null) {

      admobInterstitial.show();
      admobInterstitial = null;

    } else {
    
    }
}
  • Now first load interstitial Ad and the call function that show interstitial Ad.
InterstitialAds.loadInterstitialAd();
InterstitialAds.showAdmobInterstitial();

That’s it now restart whole application and you can see interstitial ads in your project.

Step 9: Rewarded ad.

In this step you can learn about Rewarded ads that how can you initialize that and how to load Rewarded ads.

Follow below step for Rewarded ads.

  • Create one file name is Reward.dart.
  • In that create one class name is RewardedAds.
  • In class create two variable.
late RewardedAd rewardedAd;
bool isRewardedAdReady = false;
  • Now add function for load Rewarded Ad.
static loadRewardedAd() {
    RewardedAd.load(
      adUnitId: AdHelper.rewardedAdUnitId,
      request: AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(
        onAdLoaded: (ad) {
          this.rewardedAd = ad;

          ad.fullScreenContentCallback = FullScreenContentCallback(
            onAdDismissedFullScreenContent: (ad) {
              setState(() {
                isRewardedAdReady = false;
              });
              loadRewardedAd();
            },
          );

          setState(() {
            isRewardedAdReady = true;
          });
        },
        onAdFailedToLoad: (err) {
          print('Failed to load a rewarded ad: ${err.message}');
          setState(() {
            isRewardedAdReady = false;
          });
        },
      ),
    );
  }
  • Now create one more function for show Rewarded Ad.
static showAdmobRewarded() async {
    if (admobInterstitial != null) {

      rewardedAd.show();
      rewardedAd = null;

    } else {
    
    }
}
  • Now first load interstitial Ad and the call function that show Rewarded Ad.
RewardedAds.loadRewardedAd(); 
RewardedAds.showAdmobRewarded();

That’s it now restart whole application and you can see Rewarded ads in your project.

So, that’s how you can use Google mobile ads in your project.

Hope you guys found something useful. If you have any doubts or questions do comment.

See you in the Next Article.

1 Comment

  1. ChrisH

    Does that still work? And in particular does displaying of the Android ca-app-pub-3940256099942544/6300978111 banner ad work?
    It stopped to work for me some 2 months ago and I did not touch the code that actually loads and displays the ad for almost a year. It is only the banner ad that stopped working, I also use google_mobile_ads library to display interstitial ads on both iOS and Android and it is only the banners that stopped working and only on Android.

    0
    0
    Reply

Submit a Comment

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

Subscribe

Select Categories