Add Interstitial Admob Ad with Flutter

Tiempo de lectura: 3 minutos

Today we are going to learn how we can add an Interstitial ad with Admob in Flutter

The first thing we are going to do is create the file with our ad IDs, for that we have to go to Admob and get the code that will allow us to add the banner.

Now we are going to create this file: idsAnuncios.dart

import 'dart:io';

const test = false;

String getIdInterstitial() {
  var bannerId = "ca-app-pub-3940256099942544/6300978111";
  if (Platform.isAndroid) {
    if (!test) {
      //Real ads
      bannerId = "your_android_banner_ad_id";
    } else {
      //Test ads
      bannerId = "ca-app-pub-3940256099942544/1033173712";
    }
  } else if (Platform.isIOS) {
    if (!test) {
      //Real ads
      bannerId = "your_ios_banner_ad_id";
    } else {
      //Test ads
      bannerId = "ca-app-pub-3940256099942544/4411468910";
    }
  }
  return bannerId;
}

We have added a variable that will allow us to put the ads in test mode.

We have added the default test Banner ad ID offered by Admob.

Also, we assign the ads for Android and iOS.

Where it says your_copied_code, you add the Admob code you have created.

Now we are going to add the library that will allow us to use Google ads:

google_mobile_ads

For this:

flutter pub add google_mobile_ads

Also, we will have to add the following inside pubspec.yaml to increase the minimum SDK to 2.12.0 and allow null safety

environment:
  # Update the minimum sdk version to 2.12.0 to support null safety.
  sdk: ">=2.17.0 <3.0.0"

Note: in my case as of this date it already generates projects with this version:

Now we open our AndroidManifest inside the directory: android/app/src/main/AndroidManifest.xml

And we add the application code:

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

</manifest>

In case of iOS you should add inside info.plist

<

pre class=”EnlighterJSRAW” data-enlighter-language=”generic” data-enlighter-theme=”” data-enlighter-highlight=”” data-enlighter-linenumbers=”” data-enlighter-lineoffset=”” data-enlighter-title=”” data-enlighter-group=””>
Note:
Test APP id: ca-app-pub-3940256099942544~334751171

You must add yours, generated from Admob.

Now let’s go to our main screen and let’s initialize the ads with this function:

 Future _initGoogleMobileAds() {
// Initialize Google Mobile Ads SDK
return MobileAds.instance.initialize();
}

And now we are going to create the interstitial.

interstitial.dart

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:walls_wallpapers/util/idsAnuncios.dart';

class AdInterstitial {
  static InterstitialAd? _interstitialAd;

  static Future<void> initialize() async {
    await _loadInterstitialAd();
  }

  static Future<void> _loadInterstitialAd() async {
    InterstitialAd.load(
      adUnitId: AdHelper.interstitialAdUnitId,
      request: AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (InterstitialAd ad) {
          print('Interstitial Ad loaded');
          _interstitialAd = ad;
        },
        onAdFailedToLoad: (LoadAdError error) {
          print('Interstitial Ad failed to load: $error');
        },
      ),
    );
  }

  static void showInterstitialAd() {
    if (_interstitialAd == null) {
      print('Interstitial Ad not loaded yet.');
      return;
    }

    _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
      onAdDismissedFullScreenContent: (Ad ad) {
        print('Interstitial Ad dismissed');
        // Here you can navigate to the home screen or perform another action after the ad is closed.
        _loadInterstitialAd(); // Load a new ad after the current one has been shown.
      },
    );

    _interstitialAd!.show();
  }

  static void dispose() {
    _interstitialAd?.dispose();
  }
}

class AdHelper {
  static String interstitialAdUnitId = getIdInterstitial();
}

And we add the initializer in main.dart

AdInterstitial.initialize();

And now we can load our ad wherever we want like this:

AdInterstitial.showInterstitialAd();

Or from a button for example:

ElevatedButton(
  onPressed: () {
    AdInterstitial.showInterstitialAd();
  },
  child: Text('Show Ad'),
)

And that’s it, this is the result:

Leave a Comment