Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will learn how to show local notification in flutter by using awesome notification package.
Output of below source code main.dart
About Awesome Notification – flutter package
Flutter awesome notification is a very useful & complete solution, when it comes in implementation of notification in flutter weather it’s a local notification or a push notification in flutter through firebase or any other cloud messaging services.
Let’s have a look into feature of awesome notifications
Support in creating local notification on Android, iOS and Web.
With few lines of code integrate firebase push notification.
Notification can be customized as per needs.
Add Image, custom sound, Action button & more.
OnForeground, Background or even when app is force stopped notification can be invoked.
1. [Snippet Code] Notification with only title & body text.
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: 'key1',
title:'Title for your notification',
body: 'body text/ content'
)
);
2. [Snippet Code] Notificaton with title,body & a Image NotificationLayout.
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: 'key1',
title: 'This is Notification title',
body: 'This is Body of Noti',
bigPicture: 'https://protocoderspoint.com/wp-content/uploads/2021/05/Monitize-flutter-app-with-google-admob-min-741x486.png',
notificationLayout: NotificationLayout.BigPicture
),
);
3. [Snippet Code] Scheduled Notification.
String timezom = await AwesomeNotifications().getLocalTimeZoneIdentifier(); //get time zone you are in
AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: 'key1',
title: 'This is Notification title',
body: 'This is Body of Noti',
bigPicture: 'https://protocoderspoint.com/wp-content/uploads/2021/05/Monitize-flutter-app-with-google-admob-min-741x486.png',
notificationLayout: NotificationLayout.BigPicture
),
schedule: NotificationInterval(interval: 2,timeZone: timezom,repeats: true),
);
CreateNotification class accept 3 parameters content, schedule and List of actionButtons, where content is required to be specified.
In Content: we are passing NotificationContent which then needs some data properties such as id, channelKey, title & body, and there are many other properties which can be used to customize local notification such as showing a image by using bigPicture properties to show image in notification.
Scheduling a local notification in flutter
As you see in above snippet code, we have used schedule property in createNotification(content: …., schedule:…).
You can easily set a scheduled notification by using schedule property inside createNotification class. In schedule you can make use of NotificationInterval to schedule.
schedule – NotificationInterval properties
property
description
interval
initial notification show time in seconds.
timeZone
your current location timezone
repeat (type bool)
show notification keep repeating after certain seconds, as specified in interval.
NotificationContent properties
property
type
Description
id
int
A unique number identify notification.
channelKey
String
A uniget key to identify the notification.
title
String
A header title text.
body
String
Text Content
displayOnBackground
bool
set weather noti should be displayed when user is not using your app.
displayOnForeground
bool
set weather noti should be displayed when user is using your app.
icon
String
icon for your app notification.
bigPicture
String
url/path of image to show notification thumbnail.
autoCancel
bool
noti should go when user top on it.
backgroundColor
Color
set a custom color to notify.
How to open NotificationPage when user click on Notification – flutter
So the below snippet code, will be listening to user click event & when user click on notification app will get opened & user will be navigated to ‘/NotificationPage’.
This Article, is a step-by-step tutorial on how to add flutter project to firebase orhow to connect flutter project to firebase console & Then code for push notification in flutter app with complete source code at bottom of this article.
firebase cloud push notification
What is a push Notification?
A push notification is a way of communication with your app user/customer. Now a days each & every business app, implement push notification into there application so that user get re-engaged to app whenever they get important push notification updates. Now firebase push notification technology is been rapidly growing in market to communicate with customer/app user.
Let’s quickly start by creating new flutter project & connecting flutter project to firebase.
How to connect flutter project to firebase console for cloud messaging
Video Tutorial
1. Create a new flutter project
Open any existing flutter project, where you want to add firebase push notfication or just create a new flutter project. My favorite IDE is Android Studio, you can choose your favorite IDE to build Flutter Project.
File > New > New Flutter project( give a good name to your flutter project & finish)
2. Add Firebase to your flutter app
Visit firebase.google.com, SignIn with your Google Account & go to firebase console.
Add Project
click on Add Project to create new firebase project for your flutter app.
Give a good name for firebase project
Hit create project button
Then, now our firebase project is ready, now we use need to connect our flutter project to firebase project.
3. [ANDROID] Adding Firebase to your flutter android module
To add android module of your flutter project click on android icon button on firebase console as show in below screenshot.
1. Register app in firebase project console
To get android package name, go to your flutter project [project] android > app > src > main > AndroidManifest.xml as shown in below screenshot.
Copy the package name & paste in “Android Package name” for registration of your app.
2. Download google-services.json that firebase provides
3. copy/paste the google-services.json file in your flutter android module
Now, copy/paste firebase generated google-services.json file into [project] > android > app [ paste here ]. Refer below screenshot to understand where to paste google-services.json file.
Hit the next button, now run your flutter project with mobile device connected to internet, Hurrrryy..!!! your Flutter android & iOS module is now connected to firebase project.
Now you have successfully added your flutter project into firebase console.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); // initialize firebase before actual app get start.
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
FirebaseMessaging.onBackgroundMessage will keep track of incoming push notification from firebase. Then it will transfer the message to firebaseMessagingBankgroundHandler with message parameter.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print("Handling a background message: ${message.messageId}");
//call awesomenotification to how the push notification.
AwesomeNotifications().createNotificationFromJsonData(message.data);
}
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
print("Handling a background message: ${message.messageId}");
// Use this method to automatically convert the push data, in case you gonna use our data standard
AwesomeNotifications().createNotificationFromJsonData(message.data);
}
Then once onBackgroundMessage detect any incoming message i.e. push notification message from firebase cloud messaging, you can use RemoteMessage to show notification to user using AwesomeNotification package.
optional: If you want to show notification to users locally, when users performer some action in app, then you can use local notification that can we done easily by awesome notification.
This Blog Post is on how to submit app-ads.txt file for admob verification to show ads on your Application, So let’s Begin.
Video Tutorial
Establish a app company Website
A App must have a website so that your app user can visit the website & learn more about your company and get knowledge of your application.
You should have a company website to host app-ads.txt file with a domain name.
Ofcourse, there are many alternative way to submit app-ads.txt file for free without hosting a website, such as by using app-ads-txt.com, Blogger.com and many other way: But I recommend you to do this with your own company domain website, Because it looks genuine to your app user & also google recommend you to establish your own website, instead of using any third party to fix app-ads.txt.
How to create app-ads.txt file?
look at the image below for Example of app-ads.txt.
app-ads.txt format
Note: Check the name file name must be (app-ads.txt) and the content within it must be as per format given by IAB tech Lan in order to get verified successfully.
How to create app-ads.txt file
Create a document with extension .txt file.
name the document as app-ads.txt.
SignIn to Admob account
Navigate to App > View all aps > app-ads.txt tab.
click on how to setup app-ads.txt button.
you will find a code snippet code “copy it“
and paste the code snipper into your app_ads.txt document.
Publish the app-ads.txt file on your app website
Now, Once you have created app-ads.txt file you need to publish it on your website. just upload the app-ads.txt file on root directory in website.
Uploading app-ads.txt to your website hosting in root directory
Eg: www.domain-name.com/app-ads.txt
Note: make sure your the exact website domain is listed on Google Play Console or App Store.
Now wait for at least 25 hours for admob crawler to crawl to your website app-ads.txt file.
Hurry, your have successfully sumbited and fixed the app-ads.txt file requirement for admob ads.
admob has successfully verified your app-ads.txt file
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.
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
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.
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
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 ...
),
);
}
}
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
ImportantNote: 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.
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.banner
320 x 50
AdSize.largeBanner
320 x 100
AdSize.mediumRectangle
320 x 250
AdSize.fullBanner
468 x 60
AdSize.leaderboard
728 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
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.
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.
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.
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.
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)