Home Blog Page 65

Connecting Flutter Android & iOS to Firebase & integrate push notification

0
flutter firebase push notification using awesome notificatiion package
flutter push notification

Hi Welcome to Proto Coders Point, In this firebase flutter tutorial, we will learn how to integrate firebase notification in your flutter app.

Note: We’re going to use ‘awesome_notification package‘.

This Article, is a step-by-step tutorial on how to add flutter project to firebase or how to connect flutter project to firebase console & Then code for push notification in flutter app with complete source code at bottom of this article.

firebase cloud push notification
firebase cloud push notification

What is a push Notification?

A push notification is a way of communication with your app user/customer. Now a days each & every business app, implement push notification into there application so that user get re-engaged to app whenever they get important push notification updates.
Now firebase push notification technology is been rapidly growing in market to communicate with customer/app user.

Let’s quickly start by creating new flutter project & connecting flutter project to firebase.

How to connect flutter project to firebase console for cloud messaging

Video Tutorial

1. Create a new flutter project

Open any existing flutter project, where you want to add firebase push notfication or just create a new flutter project. My favorite IDE is Android Studio, you can choose your favorite IDE to build Flutter Project.

File > New > New Flutter project( give a good name to your flutter project & finish)

2. Add Firebase to your flutter app

Visit firebase.google.com, SignIn with your Google Account & go to firebase console.

Add Project

click on Add Project to create new firebase project for your flutter app.

firebase create new project

Give a good name for firebase project

creating new firebase project

Hit create project button

Then, now our firebase project is ready, now we use need to connect our flutter project to firebase project.

3. [ANDROID] Adding Firebase to your flutter android module

To add android module of your flutter project click on android icon button on firebase console as show in below screenshot.

how to add flutter android module to firebase project

1. Register app in firebase project console

To get android package name, go to your flutter project
[project] android > app > src > main > AndroidManifest.xml as shown in below screenshot.

Copy the package name & paste in “Android Package name” for registration of your app.

2. Download google-services.json that firebase provides

3. copy/paste the google-services.json file in your flutter android module

Now, copy/paste firebase generated google-services.json file into [project] > android > app [ paste here ]. Refer below screenshot to understand where to paste google-services.json file.

where to paste google-services in flutter project

4. Add Firebase SDK

We need google services to load google-services.json file, so add a classpath of google service in your android module

project-level build.gradle file

dependencies {
    classpath 'com.android.tools.build:gradle:4.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    // add this line
    classpath 'com.google.gms:google-services:4.3.8'
}

then at bottom of project level build gradle.

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
where to add google services classpath
google services classpath

app-level build gradle

firebase bom, analytics
apply plugin: 'com.google.gms.google-services'
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics'
}

Now, We are done with adding Flutter Android Module to Firebase. Now let’s add flutter iOS module to firebase.

3. [iOS] Adding Firebase to your flutter iOS module[iphone]

1. connecting flutter iOS to firebase

Just like we did in android firebase connection, now click on iOS button in firebase console.

2. Register app – Add firebase to ios module of flutter.

where to find bundle ID of iOS flutter?

In iOS the package name key is CFBundleIdentifier in Info.plist

<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>

Which is found in Runner.xcodeproj/project.pbxproj

PRODUCT_BUNDLE_IDENTIFIER = com.example.notificationExample;

3. Download GoogleService-info.plist and paste it in iOS

where to paste google services info plist

4. Add firebase SDK using pod

5. ios firebase initialization FirebaseApp.configure()

Hit the next button, now run your flutter project with mobile device connected to internet, Hurrrryy..!!! your Flutter android & iOS module is now connected to firebase project.

Now you have successfully added your flutter project into firebase console.



Integrate firebase push notification in flutter

Now let’s start working with integrating firebase cloud messaging i.e. push notification in flutter.

1. Add dependencies required

In your flutter project open pubspec.yaml file & add this 3 dependencies that are required.

dependencies:
  awesome_notifications: ^0.0.6+7
  firebase_core: ^1.2.1
  firebase_messaging: ^10.0.1

then hit pub get, to download above package into your flutter project.

2. Initialization of Firebase services and AwesomeNotification

Firebase initialization

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(); // initialize firebase before actual app get start.

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); 

  runApp(MyApp());
}

FirebaseMessaging.onBackgroundMessage will keep track of incoming push notification from firebase.
Then it will transfer the message to firebaseMessagingBankgroundHandler with message parameter.

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  print("Handling a background message: ${message.messageId}");

  //call awesomenotification to how the push notification.
 AwesomeNotifications().createNotificationFromJsonData(message.data);
}

Awesome Notification initialization

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // firebase initialization

  AwesomeNotifications().initialize(
      null,
      [
        NotificationChannel(
            channelKey: 'basic_channel',
            channelName: 'Basic notifications',
            channelDescription: 'Notification channel for basic tests',
            defaultColor: Color(0xFF9D50DD),
            ledColor: Colors.white
        )
      ]
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);


  runApp(MyApp());
}
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.


  print("Handling a background message: ${message.messageId}");

  // Use this method to automatically convert the push data, in case you gonna use our data standard
  AwesomeNotifications().createNotificationFromJsonData(message.data);
}

Then once onBackgroundMessage detect any incoming message i.e. push notification message from firebase cloud messaging, you can use RemoteMessage to show notification to user using AwesomeNotification package.

AwesomeNotifications().createNotificationFromJsonData(message.data);

optional: If you want to show notification to users locally, when users performer some action in app, then you can use local notification that can we done easily by awesome notification.

AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 10,
          channelKey: 'basic_channel',
          title: 'Simple Notification',
          body: 'Simple body',
          bigPicture:'assets://images/protocoderlogo.png'
      )
  );


Complete Source code – Flutter Push Notification using firebase & awesome notification package

firebase push notification example
firebase push notification example

main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:awesome_notifications/awesome_notifications.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  AwesomeNotifications().initialize(
      null,
      [
        NotificationChannel(
            channelKey: 'basic_channel',
            channelName: 'Basic notifications',
            channelDescription: 'Notification channel for basic tests',
            defaultColor: Color(0xFF9D50DD),
            ledColor: Colors.white
        )
      ]
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);


  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


  int _counter = 0;

  void _incrementCounter() {
    setState(() {

      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            ElevatedButton(onPressed: (){
              //local notification 
               Notify();
            }, child: Text("Notify"))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

void Notify() async{
  // local notification
  AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 10,
          channelKey: 'basic_channel',
          title: 'Simple Notification',
          body: 'Simple body',
          bigPicture:'assets://images/protocoderlogo.png'
      )
  );

}


Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  print("Handling a background message: ${message.messageId}");

  //firebase push notification
  AwesomeNotifications().createNotificationFromJsonData(message.data);
}

How to submit app-ads.txt file – admob

0
how to fix app-ads.txt file

Hi Guys, Welcome to Proto Coders Point.

This Blog Post is on how to submit app-ads.txt file for admob verification to show ads on your Application, So let’s Begin.

Video Tutorial

Establish a app company Website

A App must have a website so that your app user can visit the website & learn more about your company and get knowledge of your application.

You should have a company website to host app-ads.txt file with a domain name.

Ofcourse, there are many alternative way to submit app-ads.txt file for free without hosting a website, such as by using app-ads-txt.com, Blogger.com and many other way: But I recommend you to do this with your own company domain website, Because it looks genuine to your app user & also google recommend you to establish your own website, instead of using any third party to fix app-ads.txt.

How to create app-ads.txt file?

look at the image below for Example of app-ads.txt.

app-ads.txt format

Note: Check the name file name must be (app-ads.txt) and the content within it must be as per format given by IAB tech Lan in order to get verified successfully.

How to create app-ads.txt file

  1. Create a document with extension .txt file.
  2. name the document as app-ads.txt.
  3. SignIn to Admob account
  4. Navigate to App > View all aps > app-ads.txt tab.
  5. click on how to setup app-ads.txt button.
  6. you will find a code snippet code “copy it
  7. and paste the code snipper into your app_ads.txt document.

Publish the app-ads.txt file on your app website

Now, Once you have created app-ads.txt file you need to publish it on your website.
just upload the app-ads.txt file on root directory in website.

Uploading app-ads.txt to your website hosting in root directory
Eg: www.domain-name.com/app-ads.txt

Note: make sure your the exact website domain is listed on Google Play Console or App Store.

Now wait for at least 25 hours for admob crawler to crawl to your website app-ads.txt file.

Hurry, your have successfully sumbited and fixed the app-ads.txt file requirement for admob ads.

admob has successfully verified your app-ads.txt file


Integrate Native Admob Ads in Flutter Application

0
native ad flutter exxample
flutter native ads between listview at random position

Hi Guys, Welcome to Proto Coders Point, this Flutter Tutorial is on how to add flutter admob native ads in flutter app.

So to show native admob ads in our flutter project, we will make use of a external library called flutter_native_admob package. Using which you can easily show cusomized native ads in your flutter android & ios application.

Brief about flutter native admob package

A Plugin that makes 70% work of developer to show admob ads into flutter project.

By using this plugin you can integrate firebase native admob ad. This plugin supports both Android & iOS platform.

Please Note: This package is not yet configured with Null safety in flutter, so to use this package your flutter project must use envirnment sdk less then 2.12.0.

environment:
  sdk: ">=2.8.0 <3.0.0"

What is Native ads? admob

A native advertising, also called as customized sponsored content ads. This are the ads that matches a application contents.

For Example:- A app has a list of items been displayed to the user you can insert a native ads similar look as of your list of items, showing native ads in between listview builder.

Advantage of native ads in app

  • Customized ads content – ads look similar to your app UI.
  • Eye Catching – App user will not feel irritated by ads.
  • Native ads are higher in click-through-rate(CTR) so the earning may be more.

Then, Now let’s start integrating native ads in flutter project.

Video Tutorial on Flutter Native Ads

Integrate Native Admob Ads in Flutter Application

1. Create a new Flutter Project

Just open any existing flutter project or create a new project in your favorite IDE. In my case, i am making use of Android Studio IDE to build flutter projects.

2. Add dependencies

In your project, open pubspec.yaml file & add the native ads dependencies under dependencies section.

dependencies:
  flutter_native_admob: ^2.1.0+3   # this Line Version may change.

Note: This package is not yet updated with nullsafety feature so kindly check if your project environment sdk version is less then 2.12.0.

3. Platform prerequisite setup needed

  • Android Setup

Open Android Studio module in Android Studio

Right click on android folder of your flutter project,

[right click] android > Flutter > Open android module in android studio.

1. Adding google services classpath

open[project]/android/app/build.gradle file.

 dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.0'     // add this google services 4.3.0
    }
2. Apply the google services plugin

at the bottom of same build.gradle file add the google services plugin.

apply plugin: 'com.google.gms.google-services'
3. Add meta-data of admob App ID in Android-Manifest.xml
<manifest ....... >
<application
     android:label="nativead"
     android:icon="@mipmap/ic_launcher">

    <!-- 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-3940256099942544~3347511713"/>  <!-- your admob adpp id

  </application>
</manifest>
  • iOS Setup
Add Admob App ID key & string value – iOS

Open[project]/ios/Runner/info.plist

you need to add a GADApplicationIdentifier<key> & exactly below key a string value of your admob app id.

and a flutter embedded_view_preview for native ad preview and set it to true.

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

 <key>io.flutter.embedded_views_preview</key>
  <true/>

properties of flutter native admob package

propertydescription
adUnitID:String
loading:indicator to show ads loading progress
error:if required, show a toast message to user about failed to load ads.
type:type of ads
NativeAdmobType.full.
NativeAdmobType.banner.
conrolller:To Control nativeadmobWidget
option:Customize ads styling for appearance.

In Options, NativeAdmobOptions there are various properties that you can use to customize your native ads appearance as per your flutter app UI. Check out pub.dev page for more.


How to use Native Admob Widget

1. Create a controller using NativeAdmobController class

final _controller = NativeAdmobController();

2. use NativeAdmob Widget to show the flutter admob ads

snippet code of NativeAdmob Widget wrapped with container

Container(
                  height: 250,
                  child: NativeAdmob(
                    adUnitID: "ca-app-pub-3940256099942544/2247696110",  //your ad unit id
                    loading: Center(child: CircularProgressIndicator()),  
                    error: Text("Failed to load the ad"),
                    controller: _controller,
                    type: NativeAdmobType.full,
                    options: NativeAdmobOptions(
                        ratingColor: Colors.red,
                        showMediaContent: true,
                        callToActionStyle: NativeTextStyle(
                          color: Colors.red,
                          backgroundColor: Colors.black
                        ),
                      headlineTextStyle: NativeTextStyle(
                        color: Colors.blue,

                      ),
                      
                      // Others ...
                    ),
                  ),
                ),
Flutter Native Ad Example
Flutter Native Ad Example

Load/show Admob Native Ads in listview.builder at random position – flutter

Complete Source Code.

main.dart

import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_admob/flutter_native_admob.dart';
import 'package:flutter_native_admob/native_admob_controller.dart';
import 'package:flutter_native_admob/native_admob_options.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {


  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> images = ['images/img1.jpg','images/img2.jpg','images/img3.jpeg','images/img4.jpg','images/img5.jpg'];

  List<Object> dataads;


  @override
  void initState() {
    super.initState();
    setState(() {
      dataads = List.from(images);

      for(int i = 0;i<2;i++){
        var min = 1;
        var rm = new Random();

        //generate a random number from 2 to 4 (+ 1)
        var rannumpos = min + rm.nextInt(4);

        //and add the banner ad to particular index of arraylist
        dataads.insert(rannumpos, nativeAdWidget());
      }
    });

  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: ListView.builder(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              itemCount: dataads.length,itemBuilder: (context,index){
                if(dataads[index] is String)
                  {
                    return  Container(
                      height: 300,
                      width: MediaQuery.of(context).size.width,
                      child: Image.asset(dataads[index])
                  );

                  }else{
                  return  Container(
                      height: 300,
                      width: MediaQuery.of(context).size.width,
                      child: dataads[index] as nativeAdWidget
                  );
                }

          }),
        )
    );
  }
}

class nativeAdWidget extends StatelessWidget {

  final _controller = NativeAdmobController();
  @override
  Widget build(BuildContext context) {
    return NativeAdmob(
      adUnitID: "ca-app-pub-3940256099942544/2247696110",
      loading: Center(child: CircularProgressIndicator()),
      error: Text("Failed to load the ad"),
      controller: _controller,
      type: NativeAdmobType.full,
      options: NativeAdmobOptions(
        ratingColor: Colors.red,
        showMediaContent: true,
        callToActionStyle: NativeTextStyle(
            color: Colors.red,
            backgroundColor: Colors.black
        ),
        headlineTextStyle: NativeTextStyle(
          color: Colors.blue,

        ),

        // Others ...
      ),
    );
  }
}


output

native ad in between listview items example
native ad in between listview items example

Monetize your flutter app with google Admob ads

0
Monitize flutter app with google admob
Monitize flutter app with google admob

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will learn how to monetize flutter app with Google Admob ads.

So, you have an flutter app published on App Store or you have completed building your flutter app & want to integrate ads into your flutter app?

Lucky, you are in a right place, I have explained the step by step process on how to get ads on your app. So let’s begin.

You need to create an Admob Account

Here is a article step by step process to create account and add app in your admob account.

  • Goto Admob.com
  • SignIn/SignUp with your Google Account.
  • Goto App > Add App
    – select, YES, if you have already published App on Appstore or NO.
  • if Published, then give the package name/URL of your app.
  • A unique App ID will be generated for your Admob ads app.
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 --> 
  • Then, Click on “create Ad Unit”.
  • An Admob ad unit will be generated.
adUnitId: 'ca-app-pub-3940256099942544/6300978111'

Use this ad unit id in your flutter app to display ads in your apps.

Now, Let’s move to flutter project where you want to integrate admob ads and display ads to your app users.

How to integrate admob ads in flutter apps

1. Add dependency: Google_Mobile_Ads Package

In your flutter project open pubspec.yaml and in dependencies section add the google mobile ads package dependencies

dependencies:
  google_mobile_ads: ^0.13.0  # version may change check it 

Important Note: project configuration required to use above google mobile ads flutter ads package.

Flutter: 1.22.0 or higher.

  • Android:
    Android Studio version 3.2 or higher.
    Target SDK version or minSDKVersion 19 and higher.
    Set CompileSdkVersion 28 or higher.
    Android Gradle Plugin 4.1 or high.

2. Android Platform Setup

Admob provided App Id should be added in AndroidManifest.xml as meta-data tag inside Application Tag.

 <application
        android:label="flutter_app_simple"
        android:icon="@mipmap/ic_launcher">

       <!-- 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-3940256099942544~3347511713"/>   // replace App id with your app id 


    </application>

Note: you need to replace App ID in android:value=” your app id”;

3. iOS Platform Setup

Update Info.plist

In your flutter project, navigate to “ios/Runner/Info.plist” open it & at bottom before end of </dict> add the below key and string.

<key>GADApplicationIdentifier</key>
   <string>ca-app-pub-3940256099942544~1458002511</string>
   <key>SKAdNetworkItems</key>
     <array>
       <dict>
         <key>SKAdNetworkIdentifier</key>
         <string>cstr6suwn9.skadnetwork</string>
       </dict>
     </array>

A GADApplicationIdentifierkey with string value of your admob App ID.
A SKAdNetworkItems ey with google;’s SKANetwrkIdentifier value of skadnetwork.

4. Initialize theMobile Ads SDK

Before you actual load ads & display then to app users, you must call ‘MobileAds.instance’, which loads mobile ads SDK.

MobileAds.instance.initialize();

5. Create an instance object of Ad Eg: BannerAd

A BannerAd instance should be provided with adUnitID, AdSize, AdRequest and a BannerAdListener.

BannerAd bAd = new BannerAd(size: AdSize.banner, adUnitId: 'ca-app-pub-3940256099942544/6300978111', listener: BannerAdListener(
        onAdClosed: (Ad ad){
          print("Ad Closed");
        },
        onAdFailedToLoad: (Ad ad,LoadAdError error){
          ad.dispose();
        },
        onAdLoaded: (Ad ad){
          print('Ad Loaded');
        },
        onAdOpened: (Ad ad){
          print('Ad opened');
        }
    ), request: AdRequest());

In above replace with your own adUnitID.

Different Banner AdSize

AdSize.banner320 x 50
AdSize.largeBanner320 x 100
AdSize.mediumRectangle320 x 250
AdSize.fullBanner468 x 60
AdSize.leaderboard728 x 90

6. Show ads – Banner ads to user

Then to load and display Admob Banner ads, you can make use of AdWidget.

AdWidget(
          ad: bAd..load(),
          key: UniqueKey(),
        ),

Here, In Ad property you need to pass the bannerAd we have created above.

Thus this will load banner ads in your flutter app, as shown in below screenshots.

Complete Source Code – Flutter Admob Monetize – Banner Ad

AdmobHelper.dart

import 'dart:io';

import 'package:google_mobile_ads/google_mobile_ads.dart';

class AdmobHelper{

  static String get bannerID => Platform.isAndroid ? 'ca-app-pub-3940256099942544/6300978111' : 'ca-app-pub-3940256099942544/6300978111';

  static initialize(){
    if(MobileAds.instance == null){
      MobileAds.instance.initialize();
    }
  }

static BannerAd getBannerAd(){
     BannerAd bAd = new BannerAd(size: AdSize.fullBanner, adUnitId: bannerID , listener: BannerAdListener(
        onAdClosed: (Ad ad){
          print("Ad Closed");
        },
        onAdFailedToLoad: (Ad ad,LoadAdError error){
          ad.dispose();
        },
        onAdLoaded: (Ad ad){
          print('Ad Loaded');
        },
        onAdOpened: (Ad ad){
          print('Ad opened');
        }
    ), request: AdRequest());

    return bAd;
  }
}

main.dartOnly Banner ads at bottom of the screen

Video Tutorial on Monitizing flutter app with google admob — Banner Ad at bottom

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() {
 WidgetsFlutterBinding.ensureInitialized();
 AdmobHelper.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Admob ad example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomepage(),
    );
  }
}

class MyHomepage extends StatefulWidget {
  @override
  _MyHomepageState createState() => _MyHomepageState();
}

class _MyHomepageState extends State<MyHomepage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text('Admob Banner Test Ads'),
      ),
      bottomNavigationBar: Container(
        child: AdWidget(
          ad: AdmobHelper.getBannerAd()..load(),
          key: UniqueKey(),
        ),
        height: 50,
      ),
    );
  }
}





Hurry! We are all set, If the test ads are working, Real-Time abs will show into your flutter application once you publish the app into AppStore, you can sit back and relax.😎.



Showing admob banner ads randomly in between listview builder

Video tutorial on flutter listview ads

Source Code

AdmobHelper.dart

import 'package:google_mobile_ads/google_mobile_ads.dart';


class AdmobHelper {

  static String get bannerUnit => 'ca-app-pub-3940256099942544/6300978111';

  static initialization(){
    if(MobileAds.instance == null)
      {
        MobileAds.instance.initialize();
      }
  }

  static BannerAd getBannerAd(){
    BannerAd bAd = new BannerAd(size: AdSize.fullBanner, adUnitId: 'ca-app-pub-3940256099942544/6300978111' , listener: BannerAdListener(
        onAdClosed: (Ad ad){
          print("Ad Closed");
        },
        onAdFailedToLoad: (Ad ad,LoadAdError error){
          ad.dispose();
        },
        onAdLoaded: (Ad ad){
          print('Ad Loaded');
        },
        onAdOpened: (Ad ad){
          print('Ad opened');
        }
    ), request: AdRequest());

    return bAd;
  }
}

main.dart

import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  AdmobHelper.initialization();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Admob ad example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomepage(),
    );
  }
}

class MyHomepage extends StatefulWidget {


  @override
  _MyHomepageState createState() => _MyHomepageState();
}

class _MyHomepageState extends State<MyHomepage> {
  late List<String> datas;   // late for null safty

  late List<Object> dataads;  // will store both data + banner ads 

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    datas = [];

    //generate array list of string
    for(int i = 1; i <= 20; i++){
      datas.add("List Item $i");
    }

    dataads = List.from(datas);

    // insert admob banner object in between the array list
    for(int i =0 ; i<=2; i ++){
      var min = 1;
      var rm = new Random();

      //generate a random number from 2 to 18 (+ 1) 
      var rannumpos = min + rm.nextInt(18);

      //and add the banner ad to particular index of arraylist
      dataads.insert(rannumpos, AdmobHelper.getBannerAd()..load());

    }

  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: dataads.length,
          itemBuilder: (context,index){
            //id dataads[index] is string show listtile with item in it
            if(dataads[index] is String)
              {
                return ListTile(
                  title: Text(dataads[index].toString()),
                  leading: Icon(Icons.exit_to_app),
                  trailing: Icon(Icons.ice_skating),
                );
              }else{
              // if dataads[index] is object (ads) then show container with adWidget
              final Container adcontent = Container(
                child: AdWidget(
                  ad: dataads[index] as BannerAd,
                  key: UniqueKey(),
                ),
                height: 50,
              );
              return adcontent;
            }

      }),
      bottomNavigationBar: Container(
        child: AdWidget(
          ad:AdmobHelper.getBannerAd()..load(),
          key: UniqueKey(),
        ),
        height: 50,
      ),

    );
  }
}


Output

flutter listview ads - randomly place ads between listview flutter


How to show Interstitial ads in flutter app

Video Tutorial

Load Interstitial ad

To Load an InterstitialAd you need to pass some parameters those are adUnitId, an AdRequest(), and an adLoadCallback:InterstitialAdLoadCallback(…..).

Below is an snippet code to load admob Interstitial Ads in flutter

 InterstitialAd.load(
        adUnitId: 'ca-app-pub-3940256099942544/1033173712',  // replace with your Admob Interstitial ad Unit ID
        request: AdRequest(),
        adLoadCallback:InterstitialAdLoadCallback(
            onAdLoaded: (InterstitialAd ad){
              _interstitialAd = ad;
            },
            onAdFailedToLoad: (LoadAdError error){
             print('InterstitialAd failed to load: $error');
            }),
    );

Ad Event Tracking

To track your ad unit, you can use FullScreenContentCallback, by using which you easily keep track of ads lifecycle, such as when the ad is shown or if user dismissed the ad that is shown.

_interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(

       onAdShowedFullScreenContent: (InterstitialAd ad){
         print("ad onAdshowedFullscreen");
       },
       onAdDismissedFullScreenContent: (InterstitialAd ad){
         print("ad Disposed");
         ad.dispose();
       },
       onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError aderror){
         print('$ad OnAdFailed $aderror');
         ad.dispose();
         //call reload of the ads
       },
       onAdImpression: (InterstitialAd ad) => print('$ad impression occurred.'),

     );

show interstitial ad to flutter app user

You can choose when to show the ad to the flutter app user, by just calling interstitial.show() method.

_interstitialAd.show();

Complete Code on how to show an interstitial ads

AdmobHelper.dart

import 'package:google_mobile_ads/google_mobile_ads.dart';


class AdmobHelper {

  static String get bannerUnit => 'ca-app-pub-3940256099942544/6300978111';

  InterstitialAd? _interstitialAd;

  int num_of_attempt_load = 0;

  static initialization(){
    if(MobileAds.instance == null)
      {
        MobileAds.instance.initialize();
      }
  }
  static BannerAd getBannerAd(){
    BannerAd bAd = new BannerAd(size: AdSize.fullBanner, adUnitId: 'ca-app-pub-3940256099942544/6300978111' , listener: BannerAdListener(
        onAdClosed: (Ad ad){
          print("Ad Closed");
        },
        onAdFailedToLoad: (Ad ad,LoadAdError error){
          ad.dispose();
        },
        onAdLoaded: (Ad ad){
          print('Ad Loaded');
        },
        onAdOpened: (Ad ad){
          print('Ad opened');
        }
    ), request: AdRequest());

    return bAd;
  }

   // create interstitial ads
  void createInterad(){

    InterstitialAd.load(
        adUnitId: 'ca-app-pub-3940256099942544/1033173712',
        request: AdRequest(),
        adLoadCallback:InterstitialAdLoadCallback(
            onAdLoaded: (InterstitialAd ad){
              _interstitialAd = ad;
              num_of_attempt_load =0;
            },
            onAdFailedToLoad: (LoadAdError error){
              num_of_attempt_load +1;
              _interstitialAd = null;

              if(num_of_attempt_load<=2){
                createInterad();
              }
            }),
    );

  }


// show interstitial ads to user
  void showInterad(){
     if(_interstitialAd == null){
       return;
     }

     _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(

       onAdShowedFullScreenContent: (InterstitialAd ad){
         print("ad onAdshowedFullscreen");
       },
       onAdDismissedFullScreenContent: (InterstitialAd ad){
         print("ad Disposed");
         ad.dispose();
       },
       onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError aderror){
         print('$ad OnAdFailed $aderror');
         ad.dispose();
         createInterad();
       }
     );

     _interstitialAd!.show();

     _interstitialAd = null;
  }


}

main.dart

import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  AdmobHelper.initialization();
  runApp(MyApp());
}

class MyApp extends StatelessWidget  {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Admob ad example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomepage(),
    );
  }
}

class MyHomepage extends StatefulWidget {
  @override
  _MyHomepageState createState() => _MyHomepageState();
}

class _MyHomepageState extends State<MyHomepage> {
  late List<String> datas;   // late for null safty
  late List<Object> dataads;  // will store both data + banner ads

AdmobHelper admobHelper = new AdmobHelper();   // object to access methods of AdmobHelper class
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    datas = [];

    //generate array list of string
    for(int i = 1; i <= 20; i++){
      datas.add("List Item $i");
    }

    dataads = List.from(datas);

    // insert admob banner object in between the array list
    for(int i =0 ; i<=2; i ++){
      var min = 1;
      var rm = new Random();

      //generate a random number from 2 to 18 (+ 1)
      var rannumpos = min + rm.nextInt(18);

      //and add the banner ad to particular index of arraylist
      dataads.insert(rannumpos, AdmobHelper.getBannerAd()..load());

    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: dataads.length,
          itemBuilder: (context,index){
            //id dataads[index] is string show listtile with item in it
            if(dataads[index] is String)
              {
                return ListTile(
                  title: Text(dataads[index].toString()),
                  leading: Icon(Icons.exit_to_app),
                  trailing: Icon(Icons.ice_skating),
                  onTap: (){
                    admobHelper.createInterad();   // call create Interstitial ads
                  },
                  onLongPress: (){
                    admobHelper.showInterad();     // call  show Interstitial ads
                  },

                );
              }else{
              // if dataads[index] is object (ads) then show container with adWidget
              final Container adcontent = Container(
                child: AdWidget(
                  ad: dataads[index] as BannerAd,
                  key: UniqueKey(),
                ),
                height: 50,
              );
              return adcontent;
            }

      }),
      bottomNavigationBar: Container(
        child: AdWidget(
          ad:AdmobHelper.getBannerAd()..load(),
          key: UniqueKey(),
        ),
        height: 50,
      ),

    );
  }
}


RewardedAds in Flutter

Load RewardedAd

To Load an RewardedAd you need to pass some parameters those are adUnitId, an AdRequest(), and an rewardedadLoadCallback:RewardedAdLoadCallback(…..).

Below is an snippet code to load admob Rewarded Ads in flutter

  RewardedAd.load(
        adUnitId: 'ca-app-pub-3940256099942544/5224354917',
        request: AdRequest(),
        rewardedAdLoadCallback: RewardedAdLoadCallback(
          onAdLoaded: (RewardedAd ad) {
            print('$ad loaded.');
            // Keep a reference to the ad so you can show it later.
            this._rewardedAd = ad;
          },
          onAdFailedToLoad: (LoadAdError error) {
            print('RewardedAd failed to load: $error');
          },
        ));

RewardedAd Event Tracking

To track your ad unit, you can use FullScreenContentCallback, by using which you easily keep track of ads lifecycle, such as when the ad is shown or if user dismissed the ad that is shown.

 _rewardedAd.fullScreenContentCallback = FullScreenContentCallback(
      onAdShowedFullScreenContent: (RewardedAd ad) =>
          print('$ad onAdShowedFullScreenContent.'),
      onAdDismissedFullScreenContent: (RewardedAd ad) {
        print('$ad onAdDismissedFullScreenContent.');
        ad.dispose();
      },
      onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
        print('$ad onAdFailedToShowFullScreenContent: $error');
        ad.dispose();
      },
      onAdImpression: (RewardedAd ad) => print('$ad impression occurred.'),
    );

show Rewarded ad to flutter app user

You can choose when to show the ad to the flutter app user, by just calling _rewardedAd.show().

_rewardedAd.show(
        onUserEarnedReward: (RewardedAd ad, RewardItem rewardItem) {
         // action to reward the app user
    });

Complete Code on How to show an Rewarded ads in flutter app

AdmobHelper.dart

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

class AdmobHelper {
  
  RewardedAd _rewardedAd;
  
  static initialization() {
    if (MobileAds.instance == null) {
      MobileAds.instance.initialize();
    }
  }
  void createRewardAd() {
    RewardedAd.load(
        adUnitId: 'ca-app-pub-3940256099942544/5224354917',
        request: AdRequest(),
        rewardedAdLoadCallback: RewardedAdLoadCallback(
          onAdLoaded: (RewardedAd ad) {
            print('$ad loaded.');
            // Keep a reference to the ad so you can show it later.
            this._rewardedAd = ad;
          },
          onAdFailedToLoad: (LoadAdError error) {
            print('RewardedAd failed to load: $error');
          },
        ));
  }

  void showRewardAd() {
    _rewardedAd.show(
        onUserEarnedReward: (RewardedAd ad, RewardItem rewardItem) {
      print("Adds Reward is ${rewardItem.amount}");
     
    });

    _rewardedAd.fullScreenContentCallback = FullScreenContentCallback(
      onAdShowedFullScreenContent: (RewardedAd ad) =>
          print('$ad onAdShowedFullScreenContent.'),
      onAdDismissedFullScreenContent: (RewardedAd ad) {
        print('$ad onAdDismissedFullScreenContent.');
        ad.dispose();
      },
      onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
        print('$ad onAdFailedToShowFullScreenContent: $error');
        ad.dispose();
      },
      onAdImpression: (RewardedAd ad) => print('$ad impression occurred.'),
    );
  }
}

RewardedAdsExample.dart

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

class RewardAdsExample extends StatelessWidget {
  AdmobHelper admobHelper = new AdmobHelper();
  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(
        title: Text("Reward Ads Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(onPressed: (){admobHelper .createRewardAd();}, child: Text("Load Reward Ads")),
            ElevatedButton(onPressed: (){admobHelper.showRewardAd();}, child: Text("Show Reward ads"))
          ],
        ),
      ),
    );
  }
}

main.dart

import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:flutter_app_simple/RewardAdsExample.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  AdmobHelper.initialization();
  runApp(MyApp());
}

class MyApp extends StatelessWidget  {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Admob ad example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: RewardAdsExample(),
    );
  }
}

How much does AdMob pay per 1000 impression?

Banner ads will give you very little revenue per 1000 impressions you can only earn about $0.50, but as you all know that google Admob pays only when ads are been clicked. some time with 1000 impression a day you can earn more than $2.00 with almost 5 -10 click( all depends on the location of the ads we clicked), if an app user from the USA clicks on your ads then you can easily earn around $0.30 – $1.00 per ad click, but with another country, it will be less most of the time.

while with native big ads will pay you around $1 dollor per 1000 impression.

What is Admob? How to Setup AdMob account

0
how to setup admob account
what is google admob

What is Google Admob?

Google Admob is an ad network platform for mobile ads by which you can monetize your android & ios application. Google Admob makes earn revenue easy with in-app ads, i.e. easy-to-use monetization platform to grow you app business.

How to setup AdMob account

1. Visit admob.google.com/home

You need to create a new Admob account or just sign In into your existing google admob account.

Fill all the details while creating new account like country, time zone, billing currency detail as shown in below screenshot & accept the adsense team & condition.

2. Add your first app with admob

Then once you have created account with admob, now you can add your first app in admob console.

If your account is new you will see option to add your first app.

else goto App section in drawer & add app

Add a new app and give a name related to your app.

3. Select platform – Monitize with admob

Now select platform either Android or iOS as per you app built.

If your app is listed in playstore or appstore select yes or no

If app is listed in play store or App store

If your Android or iOS app is already listed in playstore or app store, you need to give URL or package name of your app.

4. Create A Ad Unit

Select your desired ad unit like Banner ads, intertitial ads, rewarded ads, Native ads etc.

Next

Select the Ad Style Unit, i selected banner ads as you see in below screenshot.

Give a name to your ad unit and create ad unit

5. Done – Admob app is created with ad unit

Done, Therefore, now our app is connected with admob & ready to show ads on your app.

How to add admob to android app or iOS app.

* Now you just need to place your ads unit in your app code to load and display ads on your mobile app.

** will soon post a article on how to add admob to android app (flutter)