How add google_mobile_ads to flutter app [Banner + Interstitial + Reword]
اضبط معرف الاعلان في ملف : Androidmanifest
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value=""/>
Import the Mobile Ads SDK
قم باضافة حزمة الاعلانات المتوافقة مع اصدار نسختك
google_mobile_ads: ^0.13.4
Click Pub get
ثم اضغط على Pub get
Initialize the Mobile Ads in main.dart file
ثم اضف هذا الكود لملف : main.dart
WidgetsFlutterBinding.ensureInitialized();
AdmobHelper.initialize();
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),
Display ads code in the right place for Interstitial ads
كود ظهور الاعلانات في المكان المناسب لل Interstitial ads
admobHelper.createInterad();
admobHelper.showInterad();
Display ads code in the right place for Reword ads
كود ظهور الاعلانات في المكان المناسب لل Reword ads
admobHelper.createRewardAd();
admobHelper.showRewardAd();
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
:Out put
codelabs.developers.google
https://codelabs.developers.google.com/codelabs/admob-ads-in-flutter#0
flutter.dev
Pub Dev
https://pub.dev/packages/google_mobile_ads
تعليقات
إرسال تعليق