[Flutter] Admob

2021-05-03 hit count image

In this blog post, I will show you how to use the google_mobile_ads package to display the advertisement in Flutter

Outline

In this blog post, I will introduce how to use the google_mobile_ads package to show the Admob advertisment.

In this blog post, I will introduce how to show the Admob banner advertisment, and you can see the source code on the link below.

Admob configuration

To use Admob in Flutter, we need to use the Admobe service.

Signup Google Admob

Go to the Google Admob site and signup. It’s the same process of the signup/login for the normal service, so I just skip to explain the details.

Create Admob

Let’s see how to use Google Admob. After signin to use the Google Admob, you can see the screen like below.

signin google admob

Click the GET STARTED button on the bottom to start using Google Admob

configure admob

Select whether the app is already registered in the market. We didn’t register, so we select NO here.

configure app name on admob

Insert the app name and select the platform to use Google Admob. First, we select iOS here.

completed to configure

Done! we’ve registered Google Admob. There are details about next step.

  1. copy App ID for setting Flutter
  2. we need to configure Ad Unit in Google Admob.
  3. after releasing the app to Market, we need to link it in Google Admob.

Click NEXT: CREATE AD UNIT to go to Advertisement configuration.

select advertisement type

In here, I will show how to use Banner via react-native-firebase, so clic SELECT button on the bottom of Banner.

input banner name

Insert Banner name. This banner name just helps you find and recognize this banner on Google Admob. After inserting, Click CREATE AD UNIT button.

finished configuration

Completed to set Google Admob banner. Copy App ID and ad unit ID.

For Android, create a banner by the same way above, and create App ID and Ad Unit ID, too.

Create project

To show the Admob advertisement by the google_mobile_ads package, let’s create a new Flutter project. Execute the command below to create a Flutter project.

flutter create admob_example
cd admob_example

Install google_mobile_ads package

We need to install the google_mobile_ads package to show the Admob advertisement in Flutter project. Execute the command below to install the google_mobile_ads package.

flutter pub pub add google_mobile_ads

Configure App ID

Next, to display the Admob advertisement by the google_mobile_ads package, we need to configure the App ID to iOS/Android.

Configure App ID on Android

To configure the Admob App ID to Android, open android/app/src/main/AndroidManifest.xml file and modify it like below.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.admob_example">
   <application
        ...>
        <meta-data
              android:name="com.google.android.gms.ads.APPLICATION_ID"
              android:value="[YOUR ANDROID APP ID]"/>
        ...
    </application>
</manifest>

Configure App ID on iOS

To configure Admobe App ID to iOS, open ios/Runner/Info.plist file and modify it like below.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  ...
  <key>GADApplicationIdentifier</key>
  <string>[YOUR iOS APP ID]</string>
  <key>LSRequiresIPhoneOS</key>
  <true/>
  <key>SKAdNetworkItems</key>
  <array>
    <dict>
      <key>SKAdNetworkIdentifier</key>
      <string>cstr6suwn9.skadnetwork</string>
    </dict>
  </array>
</dict>
</plist>

how to use google_mobile_ads

Let’s see how to use the google_mobile_ads package to display Admobe advertisement. Open the main.dart file and modify it like below.

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

const Map<String, String> UNIT_ID = kReleaseMode
    ? {
        'ios': '[YOUR iOS AD UNIT ID]',
        'android': '[YOUR ANDROID AD UNIT ID]',
      }
    : {
        'ios': 'ca-app-pub-3940256099942544/2934735716',
        'android': 'ca-app-pub-3940256099942544/6300978111',
      };

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileAds.instance.initialize();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    TargetPlatform os = Theme.of(context).platform;

    BannerAd banner = BannerAd(
      listener: AdListener(
        onAdFailedToLoad: (Ad ad, LoadAdError error) {},
        onAdLoaded: (_) {},
      ),
      size: AdSize.banner,
      adUnitId: UNIT_ID[os == TargetPlatform.iOS ? 'ios' : 'android']!,
      request: AdRequest(),
    )..load();

    return Scaffold(
      appBar: AppBar(
        title: Text('Admob'),
      ),
      body: Center(
        child: Container(
          height: 50,
          child: AdWidget(
            ad: banner,
          ),
        ),
      ),
    );
  }
}

Let’s see the code one by one.

import 'package:flutter/foundation.dart';

We shouldn’t use own AD UNIT ID on the development environment to show the Admob advertisement. If you use your AD UNIT ID on the development environment, the traffic on the development environment may be considered fraudulent traffic, and your Admob account can be blocked. So, in this example, I will use kReleaseMode to check the current environment is the debug or release. To use kReleaseMode, we need to import foundation.dart.

import 'package:google_mobile_ads/google_mobile_ads.dart';

To use google_mobile_ads, we need to import it.

const Map<String, String> UNIT_ID = kReleaseMode
    ? {
        'ios': '[YOUR iOS AD UNIT ID]',
        'android': '[YOUR ANDROID AD UNIT ID]',
      }
    : {
        'ios': 'ca-app-pub-3940256099942544/2934735716',
        'android': 'ca-app-pub-3940256099942544/6300978111',
      };

If the current environment is release by checking kReleaseMode, we’ll use own AD UNIT ID that we’ve created above. If not, we’ll use the test AD UNIT ID provided by Admob.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileAds.instance.initialize();

  runApp(MyApp());
}

Next, we need to initialize MobileAds to display the Admob advertisement by google_mobile_ads. After checking Flutter is initialized by WidgetsFlutterBinding.ensureInitialized();, call await MobileAds.instance.initialize(); to initialize MobileAds.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
}

And for the simple example, I created the Stateless widget.

Let’s see the code about how to show the banner advertisement.

@override
Widget build(BuildContext context) {
  TargetPlatform os = Theme.of(context).platform;

  BannerAd banner = BannerAd(
    listener: AdListener(
      onAdFailedToLoad: (Ad ad, LoadAdError error) {},
      onAdLoaded: (_) {},
    ),
    size: AdSize.banner,
    adUnitId: UNIT_ID[os == TargetPlatform.iOS ? 'ios' : 'android']!,
    request: AdRequest(),
  )..load();

  return Scaffold(
    appBar: AppBar(
      title: Text('Admob'),
    ),
    body: Center(
      child: Container(
        height: 50,
        child: AdWidget(
          ad: banner,
        ),
      ),
    ),
  );
}

The AD UNIT ID is different between the platforms, so we need to check which platform Flutter works on. For this, I used TargetPlatform.

TargetPlatform os = Theme.of(context).platform;

And then, I created BannerAd provided by google_mobile_ads to create a banner advertisement, and use Cascade operator to call load() function to load the banner when the BannerAd is created.

BannerAd banner = BannerAd(
  listener: AdListener(
    onAdFailedToLoad: (Ad ad, LoadAdError error) {},
    onAdLoaded: (_) {},
  ),
  size: AdSize.banner,
  adUnitId: UNIT_ID[os == TargetPlatform.iOS ? 'ios' : 'android']!,
  request: AdRequest(),
)..load();

At this moment, we can use AdListener to register the callback functions to some events of the Advertisement, and use AdRequest parameters to show the banner more effectively.

Finally, we can show the Advertisement that we’ve created by using AdWidget.

AdWidget(
  ad: banner,
)

In this example, to show the advertisement simply, we’ve used the Stateless widget. If you use Stateful widget, you can dispose the advertisement like below.

@override
void dispose() {
  super.dispose();
  _banner.dispose();
}

Completed

Done! we’ve seen how to use the google_mobile_ads package to show the Admob advertisement. Next, add the advertisement on your app and earn the money!

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

Posts