Admob App open Ad in Flutter with complete guide

Spread the love

Google Admob App open ads in flutter

Implementing google admob ads in flutter is quite easy now as google has provided powerful library for implementing google ads in our application and make revenue from it. To implement google admob app open ad in your project, follow this article and make sure that you do all steps same as I shown in this article. 

We will be implementing google admob app open ads in two parts 

    1. Setting up our app to show google ads.

    2. Show google app open ads. 

 

Follow Our Youtube video for better understating: 

 

   

1. Setup Our App to show Google Admob App open Ads

1. Run below command with flutter to add google_mobile_ads in you project:

$ flutter pub add google_mobile_ads

OR

1. Add following under dependencies in your project’s pubspec.yaml file.

dependencies:

    google_mobile_ads : ^1.3.0

Now, run flutter pub get

2. Now we have to make some changes in our app level build.gradle file

compileSdkVersion 31

    defaultConfig {

        applicationId “com.example.googleAds”

        minSdkVersion 19

        targetSdkVersion 31

        multiDexEnabled true

        versionCode flutterVersionCode.toInteger()

        versionName flutterVersionName

    }

Make sure that you have compileSdkVersion 28 or higher and minSdkVersion 19 or higher.

 

3. Add AdMob ID in AndroidMenifest file.

<manifest>

    <application>

        <!– Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 –>

        <meta-data

            android:name=”com.google.android.gms.ads.APPLICATION_ID”

            android:value=”ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy”/>

    <application>

<manifest>

4. Add Following lines in your main.dart

import ‘package:google_mobile_ads/google_mobile_ads.dart’;
import ‘package:flutter/material.dart’;

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();

  runApp(MyApp());
}

Now Almost all setup is Done. It’s time to use this in our code to show Ads.

2. Show Google App open Ads in our Application

Make a new Dart file named as AppOpenAdManager.dart and add following code into it.

import 'package:google_mobile_ads/google_mobile_ads.dart';

class AppOpenAdManager {
AppOpenAd? _appOpenAd;
bool _isShowingAd = false;
static bool isLoaded=false;

/// Load an AppOpenAd.
void loadAd() {
AppOpenAd.load(
adUnitId: "ca-app-pub-3940256099942544/3419835294",
orientation: AppOpenAd.orientationPortrait,
request: const AdRequest(),
adLoadCallback: AppOpenAdLoadCallback(
onAdLoaded: (ad) {
print("Ad Loadede.................................");
_appOpenAd = ad;
isLoaded=true;
},
onAdFailedToLoad: (error) {
// Handle the error.
},
),
);
}

// Whether an ad is available to be shown.
bool get isAdAvailable {
return _appOpenAd != null;
}

void showAdIfAvailable() {
print("Called=====================================================================");
if (_appOpenAd == null) {
print('Tried to show ad before available.');
loadAd();
return;
}
if (_isShowingAd) {
print('Tried to show ad while already showing an ad.');
return;
}
// Set the fullScreenContentCallback and show the ad.
_appOpenAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (ad) {
_isShowingAd = true;
print('$ad onAdShowedFullScreenContent');
},
onAdFailedToShowFullScreenContent: (ad, error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
_isShowingAd = false;
ad.dispose();
_appOpenAd = null;
},
onAdDismissedFullScreenContent: (ad) {
print('$ad onAdDismissedFullScreenContent');
_isShowingAd = false;
ad.dispose();
_appOpenAd = null;
loadAd();
},
);
_appOpenAd!.show();
}
}

Let’s Add on SplashScreen so that we can show loading screen until our ad loads.

Make new file named as SplashScreen.dart and add following code into it.

import 'dart:async';

import 'package:demo_ads/HomePage.dart';
import 'package:flutter/material.dart';

import 'AppOpenAdManager.dart';

class SplashScreen extends StatefulWidget {
const SplashScreen({Key? key}) : super(key: key);

@override
State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
AppOpenAdManager appOpenAdManager = AppOpenAdManager();

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

//Load AppOpen Ad
appOpenAdManager.loadAd();

//Show AppOpen Ad After 8 Seconds
Future.delayed(const Duration(milliseconds: 800)).then((value) {
//Here we will wait for 8 seconds to load our ad
//After 8 second it will go to HomePage
appOpenAdManager.showAdIfAvailable();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomePage(),
),
);
});
}

@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
}

We have to make SplashScreen as home route of our app.

So, assign SplashScreen() to home of MaterialApp in your main.dart

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

void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const SplashScreen(),
);
}
}

After doing this setup, we have to listen to app event. whenever our app goes into background and comes again to foreground, we have to show app open ad. So let’s add that event listener.

Add this listener to Screen which is just after splash screen. In our case it is HomeScreen.

So, HomeScreen.dart will be our Observer or Listener File.

Now we have to add make stateful widget with WidgetsBindingObserver

Our HomePage.dart will look like this: 

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver{
@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: const Text("Google Ads"),
),
);
}
}

Add Following code to your Observer or Listener file. in our case it is HomePage.dart

AppOpenAdManager appOpenAdManager = AppOpenAdManager();
bool isPaused = false;

@override
void initState() {
// TODO: implement initState
super.initState();
appOpenAdManager.loadAd();
WidgetsBinding.instance.addObserver(this);
}

@override
void dispose() {
// TODO: implement dispose
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// TODO: implement didChangeAppLifecycleState
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.paused) {
isPaused = true;
}
if (state == AppLifecycleState.resumed && isPaused) {
print("Resumed==========================");
appOpenAdManager.showAdIfAvailable();
isPaused = false;
}
}

Final HomePage.dart Will look like this: 

import 'package:flutter/material.dart';

import 'AppOpenAdManager.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
AppOpenAdManager appOpenAdManager = AppOpenAdManager();
bool isPaused = false;

@override
void initState() {
// TODO: implement initState
super.initState();
appOpenAdManager.loadAd();
WidgetsBinding.instance.addObserver(this);
}

@override
void dispose() {
// TODO: implement dispose
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// TODO: implement didChangeAppLifecycleState
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.paused) {
isPaused = true;
}
if (state == AppLifecycleState.resumed && isPaused) {
print("Resumed==========================");
appOpenAdManager.showAdIfAvailable();
isPaused = false;
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Google Ads"),
),
);
}
}

This is all we need to show google app open ad in our application. Hope you understand.


Spread the love

2 thoughts on “Admob App open Ad in Flutter with complete guide”

  1. Pingback: Flutter how to show Admob App open Ad only when variable divisble by 3 - JTuto Mercure

    1. For that you have to store one variable in shared preference and increment it every time user open your app. And check if variable is divisible by 3 before showing ad to user.

Leave a Comment

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