Skip to content

Instantly share code, notes, and snippets.

@nooralibutt
Last active March 1, 2021 13:18
Show Gist options
  • Save nooralibutt/acfb4c1bc0bdf3e367057f8eb5c317b2 to your computer and use it in GitHub Desktop.
Save nooralibutt/acfb4c1bc0bdf3e367057f8eb5c317b2 to your computer and use it in GitHub Desktop.
Integration of ads and Firebase

Integrating of Firebase and Admob

Use the following link for detailed guide.

1. Firebase project

  1. Create firebase project and enable analytics

  2. Create Android Project with your package name and nickname like (hackbot android). Download google-services.json file and Move it into the android/app director

    • Optional Step: For sha1 creation: Use this tool keytool -list -v -alias key -keystore /Users/nooralibutt/development/FlutterWorkspace/hackbot/key123456.jks
  3. In the root-level (project-level) Gradle file (android/build.gradle), add rules to include the Google Services Gradle plugin. Check that you have Google's Maven repository.

    buildscript {
    
        repositories {
          // Check that you have the following line (if not, add it):
          google()  // Google's Maven repository
        }
    
        ...
    
        dependencies {
          ...
    
          // TODO: Add Google Services plugin
          classpath 'com.google.gms:google-services:4.3.3'
        }
    }
    
    allprojects {
        ...
    
        repositories {
          // Check that you have the following line (if not, add it):
          google()  // Google's Maven repository
          ...
        }
    }
  4. In the module (app-level) Gradle file (android/app/build.gradle), apply the Google Services Gradle plugin.

    ...
    
    // TODO: Apply google-services plugin
    apply plugin: 'com.google.gms.google-services'
    
    android {
      ...
    }
    
    ...
  5. Enable Multidex in Android Open project/app/build.gradle and check if minSdkVersion is minSdkVersion 21 otherwise

    defaultConfig {
        ...
    
        multiDexEnabled true
    }
    
    dependencies {
        ...
    
        implementation 'androidx.multidex:multidex:2.0.1'
    }
  6. In iOS, In Xcode, drag the GoogleService-Info.plist file into the Runner directory, to import the configuration file into the Xcode project.

2. Add ad_manager.dart file

  • Use this link for test IDs of Admob

  • For Facebook Test IDs append IMG_16_9_APP_INSTALL# to test id and you will get a test ad. Remember to remove this befor publishing app.

  • Add the Firebase AdMob Flutter plugin

  • Add the Facebook Audience Network plugin

  • Update AndroidManifest.xml (Android)

    • Open the android/app/src/main/AndroidManifest.xml file in Android Studio.

    • Add your AdMob app ID by adding a <meta-data> tag and entering com.google.android.gms.ads.APPLICATION_ID. If your AdMob app ID is ca-app-pub-3940256099942544~3347511713, then you need to add the following lines to the AndroidManifest.xml file. android/app/src/main/AndroidManifest.xml

      <manifest>
          ...
          <application>
             ...
              <meta-data
                  android:name="com.google.android.gms.ads.APPLICATION_ID"
                  android:value="ca-app-pub-your~id"/>
          </application>
          
      </manifest>
  • Update Info.plist (iOS)

    • Open the ios/Runner/Info.plist file in Android Studio. Add a GADApplicationIdentifier key with the string value of your AdMob app ID. For example, if your AdMob app ID is ca-app-pub-3940256099942544~1458002511, then you need to add the following lines to the Info.plist file. ios/Runner/Info.plist

      ...
      <key>GADApplicationIdentifier</key>
      <string>ca-app-pub-your~id</string>
      ...
  1. Copy this code in your first screen like this
    import 'package:firebase_core/firebase_core.dart';
    
    _initializeEveryThing() async {
        await Future.wait([
            AdManager.initAdManager(),
            Firebase.initializeApp(),
        ]);
    }

NOTE: IN iOS, Banner, Interstital and Native Ads are supported NOTE: In Pod file, set the minimum IOS deployment target version to 9.0

import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:facebook_audience_network/facebook_audience_network.dart';
import '../all_utilities.dart';
class AdManager {
// Singleton instance code
static final AdManager _instance = AdManager._();
static AdManager get instance => _instance;
AdManager._();
static Future<void> initAdManager() async {
FirebaseAdMob.instance.initialize(appId: AdManager._appId);
await FacebookAudienceNetwork.init(
testingId:
"0CAE94DF62B6C62D8EA6D89448803B48", // honor 8c Abdur Rehman Phone
);
}
// TODO: comment its contents or empty it
static String get facebookTesting => 'IMG_16_9_APP_INSTALL#';
static String get _appId {
// TODO: Update these
if (Platform.isAndroid) {
return "ca-app-pub-4423898417866629~7756342531";
} else if (Platform.isIOS) {
return "ca-app-pub-4423898417866629~9593424961";
} else {
return "Unsupported platform";
}
}
static String get bannerAdUnitId {
// TODO: Update these
if (Platform.isAndroid) {
return "ca-app-pub-4423898417866629/3817097526";
} else if (Platform.isIOS) {
return "ca-app-pub-4423898417866629/6639958568";
} else {
return "Unsupported platform";
}
}
static String get interstitialAdUnitId {
// TODO: Update these
if (Platform.isAndroid) {
return "ca-app-pub-4423898417866629/1985141103";
} else if (Platform.isIOS) {
return "ca-app-pub-4423898417866629/8136324325";
} else {
return "Unsupported platform";
}
}
static String get facebookNativeAdPlacementId {
// TODO: Update these
if (Platform.isAndroid) {
return "${facebookTesting}222861849563328_222877959561717";
} else if (Platform.isIOS) {
return "${facebookTesting}222861849563328_222885096227670";
} else {
return "Unsupported platform";
}
}
static String get facebookNativeBannerAdPlacementId {
// TODO: Update these
if (Platform.isAndroid) {
return "${facebookTesting}222861849563328_222877559561757";
} else if (Platform.isIOS) {
return "${facebookTesting}222861849563328_222885729560940";
} else {
return "Unsupported platform";
}
}
static String get facebookInterstitialAdPlacementId {
// TODO: Update these
if (Platform.isAndroid) {
return "${facebookTesting}222861849563328_222866872896159";
} else if (Platform.isIOS) {
return "${facebookTesting}222861849563328_222886062894240";
} else {
return "Unsupported Platform";
}
}
static FacebookNativeAd getFacebookAd(NativeAdType adType,
{double height, Function(NativeAdResult, dynamic) listener}) {
final adTypePlacementID = adType == NativeAdType.NATIVE_BANNER_AD
? AdManager.facebookNativeBannerAdPlacementId
: AdManager.facebookNativeAdPlacementId;
return FacebookNativeAd(
placementId: adTypePlacementID,
adType: adType,
bannerAdSize: NativeBannerAdSize.HEIGHT_100,
width: double.infinity,
height: height ?? 100,
backgroundColor: AppTheme.backgroundColor,
titleColor: AppTheme.primary,
descriptionColor: AppTheme.descriptionColor,
buttonColor: AppTheme.primary,
buttonTitleColor: AppTheme.descriptionColor,
keepExpandedWhileLoading: false,
expandAnimationDuraion: 200,
listener: (result, value) {
listener?.call(result, value);
},
);
}
static const MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
testDevices: <String>[
'75FD9557226308357210C0CBE80AEBFD', // adeel bhai tablet
'F11A4F2CCD0BB447FC573BF58881166E', // adeel bhai oppo phone
'12C7EC57A67C1E1DA69AB81FACB3CA86', // zahid nokia 6.1
'00008030-00163022226A802E',
'75792c0b6f3fb93524bfab6baf9f9d58', // hanzla's iPhone
'072D2F3992EF5B4493042ADC632CE39F', // Mi Phone
'0CAE94DF62B6C62D8EA6D89448803B48' // Abd Phone
],
nonPersonalizedAds: true,
childDirected: true,
keywords: <String>[
'Freefire',
'game',
'pubg',
'shooting',
'guide',
'diamonds',
]);
// Interstitial Ad Logic
InterstitialAd _admobInterstitialAd;
bool _isAdmobInterstitialAdReady = false;
bool _isFacebookInterstitialAdReady = false;
Function _onInterstitialClosed;
int _count = 0;
_initAdmobInterstitialAd() {
_isAdmobInterstitialAdReady = false;
_admobInterstitialAd = InterstitialAd(
adUnitId: AdManager.interstitialAdUnitId,
targetingInfo: targetingInfo,
listener: _onInterstitialAdEvent,
);
}
_loadFacebookInterstitialAd() {
FacebookInterstitialAd.loadInterstitialAd(
placementId: facebookInterstitialAdPlacementId,
listener: (result, value) {
if (result == InterstitialAdResult.LOADED)
_isFacebookInterstitialAdReady = true;
/// Once an Interstitial Ad has been dismissed and becomes invalidated,
/// load a fresh Ad by calling this function.
if (result == InterstitialAdResult.DISMISSED &&
value["invalidated"] == true) {
_onInterstitialClosed?.call();
_isFacebookInterstitialAdReady = false;
_loadFacebookInterstitialAd();
}
if (result == InterstitialAdResult.ERROR)
_isFacebookInterstitialAdReady = false;
},
);
}
loadInterstitial() {
if (_admobInterstitialAd == null) _initAdmobInterstitialAd();
if (!_isAdmobInterstitialAdReady) {
_admobInterstitialAd.load();
}
if (!_isFacebookInterstitialAdReady) {
_loadFacebookInterstitialAd();
}
}
bool _showOrLoadFacebookAd(Function onInterstitialClosed) {
if (_isFacebookInterstitialAdReady) {
this._onInterstitialClosed = onInterstitialClosed;
FacebookInterstitialAd.showInterstitialAd();
return true;
}
_loadFacebookInterstitialAd();
return false;
}
bool _showOrLoadAdmobAd(Function onInterstitialClosed) {
if (_isAdmobInterstitialAdReady) {
_admobInterstitialAd.show();
this._onInterstitialClosed = onInterstitialClosed;
return true;
}
loadInterstitial();
return false;
}
bool showInterstitial({Function onInterstitialClosed}) {
if (Random().nextInt(2) == 0) {
return _showOrLoadFacebookAd(onInterstitialClosed) || _showOrLoadAdmobAd(onInterstitialClosed);
}
return _showOrLoadAdmobAd(onInterstitialClosed) || _showOrLoadFacebookAd(onInterstitialClosed);
}
showCountedInterstitial() {
_count++;
if (_count == 5) {
showInterstitial();
_count = 0;
} else {
loadInterstitial();
}
}
_onInterstitialAdEvent(MobileAdEvent event) {
switch (event) {
case MobileAdEvent.loaded:
print('interstitial ad loaded');
_isAdmobInterstitialAdReady = true;
break;
case MobileAdEvent.failedToLoad:
_isAdmobInterstitialAdReady = false;
print('Failed to load an interstitial ad');
break;
case MobileAdEvent.closed:
_onInterstitialClosed?.call();
_admobInterstitialAd = null;
Timer(Duration(seconds: 1), loadInterstitial);
break;
default:
// do nothing
}
}
// END - Interstitial Ad Logic
}
import 'package:firebase_admob/firebase_admob.dart';
import 'package:flutter/material.dart';
import '../all_utilities.dart';
import '../services/ad_manager.dart';
class BannerAdvertisement extends StatefulWidget {
final double anchorTypeMargin;
final AnchorType anchorType;
BannerAdvertisement(
{this.anchorType = AnchorType.bottom, this.anchorTypeMargin = 0});
@override
_BannerAdvertisementState createState() => _BannerAdvertisementState();
}
class _BannerAdvertisementState extends State<BannerAdvertisement> {
BannerAd _bannerAd;
bool _isReady = false;
static bool get canDisplayBanner =>
EnvironmentVariables.isAppleApproving == false;
static AdSize _adSize =
getDeviceType() == 'tablet' ? AdSize.leaderboard : AdSize.banner;
@override
Widget build(BuildContext context) {
return AnimatedContainer(
height: canDisplayBanner && _isReady ? _adSize.height.toDouble() : 0,
duration: const Duration(milliseconds: 300),
child: Center(child: Text('Advertisement')),
);
}
@override
void initState() {
print(getDeviceType());
if (canDisplayBanner) {
_bannerAd = BannerAd(
adUnitId: AdManager.bannerAdUnitId,
size: _adSize,
targetingInfo: AdManager.targetingInfo,
listener: (MobileAdEvent event) async {
if (event == MobileAdEvent.loaded) {
setState(() => _isReady = true);
await Future.delayed(const Duration(milliseconds: 300));
_bannerAd?.show(
anchorOffset: widget.anchorTypeMargin,
anchorType: widget.anchorType);
} else if (event == MobileAdEvent.failedToLoad) {
print('ADMOB BANNER: failedToLoad');
}
},
);
_bannerAd?.load();
}
super.initState();
}
@override
void dispose() {
_bannerAd?.dispose();
_bannerAd = null;
super.dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment