Home Blog Page 66

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.dart β€” Only 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)

The Best App Development Tools in Flutter

0
Best App Development Tools for Flutter development
Best App Development Tools for Flutter development

Hi Guys, Welcome to Proto Coders Point, In this Blog Post let’s discuss on best app development tools/kits for app build with flutter.

Below I have made a list of the most effective flutter app development tools, which you can check out, learn about it and use right now for developing the best cross-platform flutter app & user-friendly UI applications. So let’s not waste time and check out the list of best Flutter development tools – App development kits.

10 Best Flutter App Development Tools

  1. Android Studio
  2. Visual Studio Code
  3. Panache
  4. Supernova
  5. Adobe Plugin
  6. Instabug
  7. RevenueCat
  8. Count.ly
  9. Appetize.io
  10. Firebase

1. Android Studio IDE Tool

The Android Studio IDE Tool is the top best flutter software development tools, This tool comes with feature like editing support, syntax highlighting, Intelligent code Editor and also an APK analyzer that you can use to check the size of a flutter app & reduce the size of the app. IDE that enables you to develop an effective, responsive and rich flutter app, Android Studio is the best app building tool & UI design tools.

Features

  • Realtime profilers.
  • Flexible build system.
  • Intelligent code editor.
  • Fast emulator.
  • APK Analyzer.
  • Visual layout editor.

How to download android studio?

2. Visual Studio Code IDE

Visual Studio IDE is mostly used for developing Web Application but currently, Visual Studio is rapidly growing in Flutter development, Developers are using VSCode to build cross-platform app development like React Native & Flutter app.

VSCode is been developed by Microsoft and it’s a free & open-source code editor tool that is available for Windows, Linux & Mac OS.

VSCode is easy & simple to use and app build with flutter. Download VSCode

3. Panache – Flutter Material Theme editor

Panache a flutter material theme editor that helps you to create beautiful themes that you can easily integrate into your flutter applications.

Use panache to build customize widget UI Design, give shape to it and export the panache material theme as .dart file.

Currently many flutter developers are making use of this awesome flutter tool. learn more

4. Supernova

Supernova is a designing took used to create a beautiful UI code. recently supernova team has added support for the flutter platform too,

By Using supernava it is feasible to create flutter app using supernova and make modification to your flutter app in real-time.

The Best thing so supernova is it allows you to use Adobe XD UI or Sketch just by importing it here. Supernova promises you a flexible automation platform.

5. Adobe Plugin

Adobe XD has created a new plugin for flutter UI Development. This Flutter Adobe Plugin convert your mobile app designs into a flutter widget code, provide you with a .dart file that you can easily place in your flutter codebase.

6. InstaBug

Every app that is been developed will have some kind of hidden bugs that not even the developer or tester detect during the testing phase. You can use a tool called Instabug, it provides real-time contextual insights into your mobile application.

Flutter Developers use Instabug for bug reposting, in-app crash reporting, conducting a survey or ask your app users a new feature requirement request.

You can easily integrate instabugs flutter SDK in your flutter project and turn on real-time bug reposting and analysis your app usage.

7. RevenueCat

RevenueCat is very useful when you want to integrate in-app purchase or add a monthly subscription plan for your premium users. basically, RevenueCat is a purchase or subscription management tool. You can install Revenue Purchase SDK in your flutter project and easily manage your app business.

This also support in Android, iOS and many other platform where you want to integrate in-app purchase.

8. Count.ly – A Analytics tools

It’s an Open source analytic tools, Count.ly allows you to monitor your audience, and check all the analytics of how your app is performing, with this tool, you can track your app KPIs metric and check out how your apps are growing. They also provide you with a paid version using which you can send a push notification, extra feature flags, as well an A/B testing Feature.

9. Appetize.io

Run the native mobile app in your browser itself. Appetize is a cross-platform mobile app development took that allows you to run native app in any browser in HTML or JavaScript format. Appetize is used for streamline app demos, customer support, training, testing and more.

more over this tools will reduce time-to-market and lauch apps faster.

10. Firebase

A Firebase is a cross-platform solution a platform service provided by Google. Firebase is a very useful tool that you can integrate into your flutter project.

By using firebase you can build a complete back end API. This also provides real-time database, cloud database, ML function, firebase push notification, firebase cloud messaging, crash reposting, analytic and many more.

Conclusion

With the list of best app development tools, you can make your flutter app development project faster and in efficient way.

How to disable/make button invisible in flutter

0
How to disable or make button invisible in flutter
How to disable or make button invisible in flutter

Hi, Guys Welcome to Proto Coders Point, In this fluter tutorial we will learn how to disable a button in flutter & also learn how to make flutter raisedbutton invisibility when not in use so that we can prevent a button from being clicked twice accidentally.

Preventing a button from being clicked twice accidentally

Sometimes what happens is when a user wants to submit a form or perform an action when a button is clicked but accidentally a submit button or flutter raisedbutton gets clicked twice, due to flutter button getting clicked double-time accidentally, double data entry get stored or user perform task twice or face some problem while using your flutter app.

So to prevent this you need to disable further onClick event on button, until the task or the process get completed.

How to enable/disable a button in a flutter – OnClick disable button

Step to follow to enable/disable a button in flutter app.

Video Tutorial

1. Create a boolean variable isButtonClickable

Under StatefullWidget create a boolean variable that we can use to check if button is disabled or enabled.

bool isButtonClickable = true;

initially, as per your app requirement you can keep it either to true or false, in my case i am keep it to true.

2. Create a flutter button ( ElevatedButton) with onPressed property

In the below Snippet Widget Button Code, Depending on the value of isButtonClickable, I am setting text to button either Clickable or Not Clickable,

Then in onPressed() i am using if statement to check if button is Enabled, if Enabled then call the method to perform action/task else do nothing.

ElevatedButton(
              onPressed: () {
                if (isButtonClickable) {
                  ButtonClicked();
                }
              },
              child: Text(
                isButtonClickable?"Clickable":"Not Clickable",
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),

3. Create a method/function which perform some task.

Then, when a button is pressed, the method/function is called, in which by using Flutter State Management (setState()), I am updating isButtonClickable to false, Which make button disable.

That means now user will not be able to click button again twice by mistake.

NOTE: Just, for Example, I am using Future.delayed to make isButtonClickable = true after certain duration (seconds), so that it can be clickable after some time.

In your case as per your project, you can perform an action like, for example, a data is getting submitted to the database & depending on server response (success) you can clean the form and enable button or simply navigate the user to another flutter page.

Note: you may also show a circular progress indicator during a process

  void ButtonClicked() async {

    Duration time = Duration(seconds: 5);

    setState(() {
      isButtonClickable = false;                     //make the button disable to making variable false.
      print("Clicked Once");

      Future.delayed(time,(){
        setState(() {
          isButtonClickable = true;                    //future delayed to change the button back to clickable
        });

      });
    });
  }

4. [Optional] Make Button Invisible

If you want to make the button invisible, until any task or process is getting performed you can simply wrap the ElevatedButton Widget with the Visibility widget and use the visible property & set it to true or false.

Visibility(
              visible: isButtonClickable,
              child: ElevatedButton(
                onPressed: () {
                  if (isButtonClickable) {
                    ButtonClicked();
                  }
                },
                child: Text(
                  isButtonClickable?"Clickable":"Not Clickable",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
  ),

Complete Source Code – onClick disable button flutter

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:assets_audio_player/assets_audio_player.dart';

void main() => 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 Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ButtonDisable(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  late AnimationController
      iconController; // make sure u have flutter sdk > 2.12.0 (null safety)

  bool isAnimated = false;
  bool showPlay = true;
  bool shopPause = false;

  AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    iconController = AnimationController(
        vsync: this, duration: Duration(milliseconds: 1000));

    audioPlayer.open(Audio('assets/sound/bobbyrichards.mp3'),
        autoStart: false, showNotification: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("Playing Audio File Flutter"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.network(
                "https://i.pinimg.com/originals/f7/3a/5b/f73a5b4b7262440684a2b5c39e684304.jpg",
                width: 300,
              ),
              SizedBox(
                height: 30,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  InkWell(
                    child: Icon(CupertinoIcons.backward_fill),
                    onTap: () {
                      audioPlayer.seekBy(Duration(seconds: -10));
                    },
                  ),
                  GestureDetector(
                    onTap: () {
                      AnimateIcon();
                    },
                    child: AnimatedIcon(
                      icon: AnimatedIcons.play_pause,
                      progress: iconController,
                      size: 50,
                      color: Colors.black,
                    ),
                  ),
                  InkWell(
                    child: Icon(CupertinoIcons.forward_fill),
                    onTap: () {
                      audioPlayer.seekBy(Duration(seconds: 10));
                      audioPlayer.seek(Duration(seconds: 10));
                    },
                  ),
                ],
              ),
            ],
          ),
        ));
  }

  void AnimateIcon() {
    setState(() {
      isAnimated = !isAnimated;

      if (isAnimated) {
        iconController.forward();
        audioPlayer.play();
      } else {
        iconController.reverse();
        audioPlayer.pause();
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    iconController.dispose();
    audioPlayer.dispose();
    super.dispose();
  }
}

class ButtonDisable extends StatefulWidget {
  @override
  _ButtonDisableState createState() => _ButtonDisableState();
}

class _ButtonDisableState extends State<ButtonDisable> {
  bool isButtonClickable = true;

  void ButtonClicked() async {
    Duration time = Duration(seconds: 5);
    setState(() {
      isButtonClickable = false;
      print("Clicked Once");

      Future.delayed(time,(){
        setState(() {
          isButtonClickable = true;
        });

      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Visibility(
              visible: isButtonClickable,
              child: ElevatedButton(
                onPressed: () {
                  if (isButtonClickable) {
                    ButtonClicked();
                  }
                },
                child: Text(
                  isButtonClickable?"Clickable":"Not Clickable",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}