Flutter-How to earn money with Google AdMob? — Part 1

Burak Akten
7 min readMay 17, 2023

Hello Flutter lovers 💜 😄 💜

This tutorial will go over how to earn money with Google AdMob in your Flutter applications. I am planing to tell creating Google AdMob account and add some Google Ads in your applications step by step.

In this tutorial, I will show you how to add Banner Ad, Interstitial Ad and Rewarded Ad in your Flutter app.

Firstly, let’s create a single page app that called google_admob_tutorial (you can give a different name) and replace the code of the file that named main.dart with below code.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Google AdMob Tutorial',
theme: ThemeData(primarySwatch: Colors.blue),
home: const MyHomePage(title: 'Google AdMob Tutorial Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Spacer(),
_buildButton(title: "Show Interstitial Add", onTap: () {}),
_buildButton(title: "Show Rewarded Add", onTap: () {}),
Spacer(),
//Todo add here banner add implementation
],
),
),
);
}

Widget _buildButton({required Function() onTap, required String title}) {
return Container(
margin: EdgeInsets.all(8),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey, width: 1),
),
height: 50,
alignment: Alignment.center,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text(title, textAlign: TextAlign.center),
),
),
);
}
}

Google AdMob Side

Now let’s create AdMob account. Open below link and create your AdMob account by following instructions.

After creating your account, you will see a screen like below then click Add App button.

Now I assume that your application is not listed on any store and I will show you implementation for Android part. There isn’t much difference between Android and iOS. If you learn one part, it’s easy to implement for other platform.

So select Android and No options from the screen that appear after selection add app option. Then write down the name and click Add App button. After that the project created for Google AdMob side now it’s time to create ad units.

Creating Ad Units

Now It’s time to create Banner Ad unit, Interstitial Ad unit and Rewarded Ad unit.

From the screen click Add Ad Unit button and select Banner Ad then give a name for that unit and create it. After that you will see the id of this banner ad and app id. Copy these information. We will use them in our implementation.

After creating banner ad unit, do same things for other ad types. Then save all unit informations. There is one different thing for creating Rewarded dd unit that you need to enter reward count. For now 1 is enough.

We will use this ids when we release the application (by replace default with these that you created). For testing we use default values provided to us by Google.

//Default ids
//Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
final String testBannerAdId = "ca-app-pub-3940256099942544/6300978111";
final String testInterstitialAdId = "ca-app-pub-3940256099942544/1033173712";
final String testRewardAdId = "ca-app-pub-3940256099942544/5224354917";

Implementing Mobile Side

Firstly, we need to add necessary add dependency into pubspec.yaml file of project.

dependencies:
google_mobile_ads: ^x.y.z

Or we can run this command on command line when you in the project folder.

$ flutter pub add google_mobile_ads

For more information about google_mobile_ads:

After that we need to add meta-data into AndroidManifest.xml file that is in android folder in order to enable this application to show add. You need to change the APPLICATION_ID with your ID that you create from AdMob side when you release the app.

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

Also you need to change minSdkVersion to 19 from the file build.gradle (android/app/build.gradle).

Lastly, you may need to enable multidex support for your project. To do that you can run flutter run — debug command then press “y” to add that support when asking.

Now we are ready to write some codes from Flutter side. I will not use any clean architecture like MVVM for this project. I will focus on implementing for showing ads. If you want to learn about MVVM architecture, you can read my other blogs.

I want to create a file that named ad_service.dart which includes the implementation of ad loading methods. Let’s firstly add banner ad load method like this.

import 'package:google_mobile_ads/google_mobile_ads.dart';

class AdService {
final String testBannerAdId = "ca-app-pub-3940256099942544/6300978111";
final String testInterstitialAdId = "ca-app-pub-3940256099942544/1033173712";
final String testRewardAdId = "ca-app-pub-3940256099942544/5224354917";

BannerAd loadBannerAd({String? adId, AdEventCallback? onAdLoaded, AdLoadErrorCallback? onFailed}) {
return BannerAd(
adUnitId: adId ?? testBannerAdId,
request: const AdRequest(),
size: AdSize.banner,
listener: BannerAdListener(
onAdLoaded: onAdLoaded,
onAdFailedToLoad: onFailed,
),
)..load();
}
}

In this method, we can give the adId and listener method from where we use. So let’s use it from screen by adding this lines into _MyHomePageState class :

class _MyHomePageState extends State<MyHomePage> {
BannerAd? _bannerAd;

@override
void initState() {
super.initState();
_loadBanner();
}

void _loadBanner() {
_bannerAd = AdService().loadBannerAd(
onAdLoaded: (ad) => _bannerAd = ad as BannerAd,
onFailed: (_, __) => _bannerAd?.dispose(),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
.
.
.
Spacer(),
if (_bannerAd != null)
SafeArea(
child: Container(
height: _bannerAd!.size.height.toDouble(),
width: _bannerAd!.size.width.toDouble(),
child: AdWidget(ad: _bannerAd!),
),
),
],
),
),
);
}

.
.
.
}

What I do here?

Firstly, I load the banner ad by calling loadBannerAd from AdService and use this ad with AdWidget to show on the screen.

So this is the most easy ad to show. Let’s see other ones…

We need to add two other load method into AdService class as before then calling these methods same from screen as Banner Ad.

//ad_service.dart
void loadInterstitialAd({String? adId, GenericAdEventCallback<Ad>? onAdLoaded, FullScreenAdLoadErrorCallback? onFailed}) {
InterstitialAd.load(
adUnitId: adId ?? testInterstitialAdId,
request: const AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: onAdLoaded != null ? onAdLoaded : (ad) {},
onAdFailedToLoad: onFailed != null ? onFailed : (error) {},
),
);
}

void loadRewardedAd({String? adId, GenericAdEventCallback<RewardedAd>? onAdLoaded, FullScreenAdLoadErrorCallback? onFailed}) {
RewardedAd.load(
adUnitId: adId ?? testRewardAdId,
request: const AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: onAdLoaded != null ? onAdLoaded : (ad) {},
onAdFailedToLoad: onFailed != null ? onFailed : (error) {},
),
);
}
----------------------------------------------------------------------------
//main.dart
InterstitialAd? _interstitialAd;
RewardedAd? _rewardedAd;

void _loadInterstitial() {
AdService().loadInterstitialAd(
onAdLoaded: (ad) => _interstitialAd = ad as InterstitialAd,
onFailed: (error) => _interstitialAd?.dispose(),
);
}

void _loadRewarded() {
AdService().loadRewardedAd(
onAdLoaded: (ad) => _rewardedAd = ad,
onFailed: (error) => _rewardedAd?.dispose(),
);
}

We loaded ads and now we need to show them when clicking the relative button. For these ads we don’t need a widget to show.

Interstitial Button On Click

We need to call show method over the InterstitialAd object that we loaded before.

_buildButton(
title: "Show Interstitial Add",
onTap: () async {
if (_interstitialAd != null) await _interstitialAd!.show();
},
),

Rewarded Button On Click

Same as InterstitialAd, we need to call show method over the RewardedAd object that we loaded before.

_buildButton(
title: "Show Rewarded Add",
onTap: () async {
if (_rewardedAd != null)
await _rewardedAd!.show(
onUserEarnedReward: (_, __) async {
//Do what ever you want, user gained the reward.
Fluttertoast.showToast(
msg: "Congratulation, You get your reward.",
timeInSecForIosWeb: 3,
gravity: ToastGravity.TOP
);
},
);
}),

For rewarded ad show method, we can use onUserEarnedReward parameter to do what ever we want when user get the reward. For example, if your app kind of game application and user finish all health, you can give one more health after watching ad by using this parameter.

That’s all things to tell you about how to show ads on your Flutter app. Do not forget to change ad unit ids and app id before release.

You can see all code from that repo:

Last but not least

When everything done and you release your app on store. There is one more and significant thing about getting paid from these ads. This is Setting up an app-ads.txt file for your app. Acctualy this is the must for getting paid. There are various way to do that but I will planning to use Firebase Hosting for that. I will mention about this topic in the next part.

Conclusion:

In this article, I wanted to show you how to create your ad units from Google AdMob and use them on your Flutter applications. I hope I show everything clear.

They will make your coding life interesting and clear. They are not confusing that you think.

Do not hesitate to get in touch with me about any Flutter things☺️

I hope this article useful for you. Thank you for your time. If you liked this article please leave some 👏 and share it with friends. 🤩

Wait for another topic from me Flutter lovers 💜 😄 💜

Happy coding times 🥳🤩

Get in touch with me and see my mobile applications on this link.

Burak Akten, Flutter Developer at Profe Information Systems👈

--

--