How add google_mobile_ads to flutter app [Banner + Interstitial + Reword]

How add google_mobile_ads to flutter app [Banner + Interstitial + Reword]

أضافة اعلانات admob [بانر + إعلان بيني + اعلان بمكافأة] الى تطبيق فلاتر 

How add google_mobile_ads to flutter app [Banner + Interstitial + Reword]

لاتنسو الاشتراك بالقناة








Prerequisites of Google Mobile Ads for Flutter app


Add the AdMob App ID to AndroidManifest.xml

اضبط معرف الاعلان في ملف : Androidmanifest


 <meta-data

    android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value=""/>


Update AndroidManifest.xml


Import the Mobile Ads SDK

قم باضافة حزمة الاعلانات المتوافقة مع اصدار نسختك

google_mobile_ads: ^0.13.4

Click Pub get

ثم اضغط على Pub get

Integrating Google Mobile Ads SDK into a Flutter app

 Initialize the Mobile Ads  in main.dart file

ثم اضف هذا الكود لملف : main.dart

WidgetsFlutterBinding.ensureInitialized();
AdmobHelper.initialize();


Initialize the Mobile Ads SDK


Create a new file called ad_mob_helper

قم بانشاء ملف جديد باسم : ad_mob_helper


Call the ad library in the file: ad_mob_helper

قم ب استدعاء مكتبة الاعلانات في ملف : ad_mob_helper

import 'package:google_mobile_ads/google_mobile_ads.dart';


Add ad codes: banner ads + interstitial ads + reword ads

Inside ad_mob_helper . file

 قوم ب اضافة اكواد  الاعلانات  : banner ads + interstitial ads + reword ads

داخل ملف ad_mob_helper




class AdmobHelper {
static String get bannerUnit => ' ca-app-pub-3940256099942544/6300978111';
late RewardedAd _rewardedAd;
InterstitialAd? _interstitialAd;
int num_of_attempt_load = 0;

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

static BannerAd getBannerAd() {
BannerAd bAd = new BannerAd(
size: AdSize.banner,
adUnitId: bannerUnit,
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;
}

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.'),
);
}
}



Then we put the ad display code in the appropriate place for banner ads

ثم نضع كود ظهور الاعلانات في المكان المناسب لل banner ads


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


add google mobile ads banner admob to flutter app




banner admob flutter app


Display ads code in the right place for Interstitial ads

كود ظهور الاعلانات في المكان المناسب لل Interstitial ads

admobHelper.createInterad();
admobHelper.showInterad();


add google mobile ads interstitial admob to flutter app


interstitial admob flutter app




Display ads code in the right place for Reword ads

كود ظهور الاعلانات في المكان المناسب لل Reword ads

admobHelper.createRewardAd();
admobHelper.showRewardAd();


add google mobile ads reword admob to flutter app



reword admob flutter app



And then we add the class identifier in the same file as placing the ad code

 وبعد ذلك نضيف معرف الكلاس في نفس ملف وضع كود الاعلان


final AdmobHelper admobHelper = new AdmobHelper();


Here is the complete file code:

هنا اكواد الملف كامل:

main.dart


import 'package:flutter/material.dart';

import 'ad_mob_helper.dart';
import 'first_route.dart';

void main() {
WidgetsFlutterBinding.ensureInitialized();
AdmobHelper.initialize();
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstRoute(),
));
}


ad_mob_helper


import 'package:google_mobile_ads/google_mobile_ads.dart';

class AdmobHelper {
static String get bannerUnit => ' ca-app-pub-3940256099942544/6300978111';
late RewardedAd _rewardedAd;
InterstitialAd? _interstitialAd;
int num_of_attempt_load = 0;

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

static BannerAd getBannerAd() {
BannerAd bAd = new BannerAd(
size: AdSize.banner,
adUnitId: bannerUnit,
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-9106597513547349/4275619601',
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;
}

void createRewardAd() {
RewardedAd.load(
adUnitId: 'ca-app-pub-9106597513547349/6821891892',
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.'),
);
}
}


first_route


import 'package:flutter/material.dart';
import 'package:flutterads/second_route.dart';
import 'package:flutterads/third_route.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'ad_mob_helper.dart';

class FirstRoute extends StatefulWidget {
@override
_FirstRouteState createState() => _FirstRouteState();
}

class _FirstRouteState extends State<FirstRoute> {
final AdmobHelper admobHelper = new AdmobHelper();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Welcome in ads test"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
padding: EdgeInsets.all(50),
child: ElevatedButton(
onPressed: () {
admobHelper.createInterad();
admobHelper.showInterad();
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()),
);
},
child: Text('interstitial ads'),
),
),
SizedBox(
height: 5,
),
Container(
padding: EdgeInsets.all(50),
child: ElevatedButton(
onPressed: () {
admobHelper.createRewardAd();
admobHelper.showRewardAd();
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ThirdRoute()),
);
},
child: Text('Reword ads'),
),
),
],
),
bottomNavigationBar: Container(
child: AdWidget(
ad: AdmobHelper.getBannerAd()..load(),
key: UniqueKey(),
),
height: 50),
);
}
}

secoend_route


import 'package:flutter/material.dart';
import 'package:flutterads/third_route.dart';

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

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.purple,
appBar: AppBar(
title: const Text("Interstitial ads"),
),
body: Center(
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.all(50),
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [new Image.asset("assets/icon.png")],
),
),
Container(
padding: EdgeInsets.only(top: 50),
margin: EdgeInsets.only(left: 45, right: 45),
child: RaisedButton(
textColor: Colors.white,
splashColor: Colors.red,
color: Colors.blue,
onPressed: () {},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Welcome in INterstitial ads',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 20),
),
],
),
),
),
]),
),
);
}
}


third_route


import 'package:flutter/material.dart';

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

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.purple,
appBar: AppBar(
title: const Text("Reword ads"),
),
body: Center(
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.all(50),
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [new Image.asset("assets/icon.png")],
),
),
Container(
padding: EdgeInsets.only(top: 50),
margin: EdgeInsets.only(left: 45, right: 45),
child: RaisedButton(
textColor: Colors.white,
splashColor: Colors.red,
color: Colors.blue,
onPressed: () {},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0))),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Welcome in Reword ads',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 20),
),
],
),
),
),
]),
),
);
}
}


add imagi to pubspec.yaml

أضف imagi إلى ملف pubspec.yaml


icon.png

flutter icon



add imagi to pubspec.yaml

:Out put


:Our resurse

codelabs.developers.google

https://codelabs.developers.google.com/codelabs/admob-ads-in-flutter#0

flutter.dev

https://flutter.dev/?gclid=Cj0KCQjwssyJBhDXARIsAK98ITTVr1TEtQmoFAWi7M9XiTj5pP_WB6Ghamtj2qeoOPBYVRMFTSvYHsAaAqe4EALw_wcB&gclsrc=aw.ds

Pub Dev

https://pub.dev/packages/google_mobile_ads





تعليقات