Sunday, 22 November 2020

Flutter-Setting up AdMob with flutter Project

 


Once you created your dream project on flutter and published you app on the playStore, you can also monentize your apps by using google admob, its like the Google adsense which you might have heard.
Before moving forward you should have a google adMob account, you can create one by using this link 

and once you are done you can follow the below steps:

  1. Create the ad unit on the AbMob dashboard of your choice like banner ad.
  2. You will be given 2 ids when it is created: App id and Ad Unit id, keep these ids handy as these will be helpful while setting up in the flutter project
  3. Now move to the VS code for setting up the details in the project.
  4. Navigate to the Android/app/src/main and open AndroidManifest.xml file and add the below entry below 
<application
        -------------------------
--------------------------------------->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="YOUR_APP_ID"/>
//Add your app id in place of YOUR_APP_ID

    5. Now we need to add firebase dependencies in the pubspec.yaml file. Add the below packages
firebase_admob^0.10.2
  firebase_core^0.5.2

    6. Now save the file and let the Vs code to download the packages and if doesnot happen you can execute=> flutter get pub 
    7. Now we need to get the firebase installed for the project, move to the firebase website and create the project and android app option and get the google-services.json file , that is to be copied to the location=> android/app
    8. open build.graddle file on location android/app and add the below dependencies tag

dependencies {
    ----------------------
    implementation platform('com.google.firebase:firebase-bom:26.1.0')
    ----------------------
    implementation 'com.google.firebase:firebase-analytics:18.0.0'
    implementation 'com.google.android.gms:play-services-basement:17.5.0'
}


9. now in android/build.graddle add the missing in classpath dependencies

 dependencies {
        -----------------------
        classpath 'com.google.gms:google-services:4.3.4'
    }


10. Now with this we can move to our dart code for getting the ads to be displayed

import 'package:firebase_admob/firebase_admob.dart';


it should be stateful widget, and in state widget, we can do a below
 static const MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
    nonPersonalizedAds: false,
    keywords: <String>['Finance''Mario'],
  );

  BannerAd _bannerAd;
  InterstitialAd _interstitialAd;

  BannerAd createBannerAd() {
    return BannerAd(
        adUnitId: 'YOUR_BANNER_AD_ID',
        //Change BannerAd adUnitId with Admob ID
        size: AdSize.banner,
        targetingInfo: targetingInfo,
        listener: (MobileAdEvent event) {
          print("BannerAd $event");
        });
  }

  InterstitialAd createInterstitialAd() {
    return InterstitialAd(
        adUnitId: 'YOUR_INTERSTITIAL_AD_ID',
        //Change Interstitial AdUnitId with Admob ID
        targetingInfo: targetingInfo,
        listener: (MobileAdEvent event) {
          print("IntersttialAd $event");
        });
  }

  @override
  void initState() {
    FirebaseAdMob.instance
        .initialize(appId: 'YOUR_APP_ID');
    //Change appId With Admob Id
    _bannerAd = createBannerAd()
      ..load()
      ..show();
    super.initState();
  }

  @override
  void dispose() {
    _bannerAd.dispose();
    _interstitialAd.dispose();
    super.dispose();
  }



this will display banner add and for the intertitial add on click we can use the below :

body: Center(
            child: RaisedButton(
          child: Text('Click on Ads'),
          onPressed: () {
            createInterstitialAd()
              ..load()
              ..show();
          },
        )),


Flutter- Storing Data in device storage on SQL DB

 For SQL storage in the device we need to first package from pub.dev named sqflite  and path package which are required for setting up DB and to create the path for the device respectively.

We can use below code for the DB connection setup inside Dbhelper class(name can be changed)

 static Future<sql.DatabasedbConnection() async {
    final dbPath = await sql.getDatabasesPath();

    return await sql.openDatabase(
      path.join(dbPath, 'users.db'),
      onCreate: (db, version) {
        return db.execute(
            'CREATE TABLE users_tx (id TEXT PRIMARY KEY,usage TEXT,txAmount REAL,
    txDate TEXT,category TEXT,currencyid INTEGER)');
      },
      version: 5,
    );
  }

in this openDatabase function will check if DB is present at the path given and if found it will return it and  else it will execute oncreate partt and create the Db and executing it and returning the Database

for this we will need to have imports

import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart' as pathProvider;


Now this databse can be used wuth other methods in the same class which can be used from other widgets directly without initializing the class as we are making these methods as static


  static Future<List<Map<Stringdynamic>>> selectData(String table) async {
    final db = await DBHelper.dbConnection();

    return await db.query(table);
  }

These all will be Future as these are async functions, below are the some other moths which can also be used

static Future<intupdateData(String table, TransactionData td) async {
    final db = await DBHelper.dbConnection();

    return await db.update(table, {
      'id': td.id,
      'usage': td.usedFor,
      'txAmount': td.txAmount,
      'txDate': td.txDate.toIso8601String(),
      'category': td.category,
      'currencyid': td.currencyid,
    });
  }

  static Future<intdeleteData(String table, String id) async {
    final db = await DBHelper.dbConnection();

    return await db.delete(table, where: 'id==?', whereArgs: [id]);
  }


Flutter-Setting up AdMob with flutter Project

  Once you created your dream project on flutter and published you app on the playStore, you can also monentize your apps by using google ad...