Recently flutter announcing the release of Google Mobile Ads for Flutter a new SDK that works with AdMob and AdManager to offer a variety of ad formats, including banner, interstitial, native, and rewarded video ads for flutter
And I want to monetize my flutter app by displaying ads through AdMob. how can we set up and integrate google mobile ads in our flutter app
The Google Mobile Ads SDK for Flutter currently supports loading and displaying banner, interstitial (full-screen), native ads, and rewarded video ads
To Integrating Google Mobile Ads SDK into a Flutter app, which you will do here
For Prerequisites: https://pub.dev/packages/google_mobile_ads#prerequisites
Adding the Google Mobile Ads plugin as a dependency
add the Google Mobile Ads plugin as a dependency to the pubspec.yaml
file located at the root of the project.
dependencies:
google_mobile_ads: ^0.11.0+1
Import to in your Dart code, you can use:
import 'package:google_mobile_ads/google_mobile_ads.dart';
Setup for Specific Platform
iOS
Update your Info.plist
Open the ios/Runner/Info.plist
file in Android Studio.
add a GADApplicationIdentifier
key with a string value of your AdMob app ID (identified in the AdMob UI) as shown below:
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-################~##########</string>
Android
Update AndroidManifest.xml
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
. as shown below. You can find your App ID in the AdMob UI. For android:value
insert your own AdMob App ID in quotes, as shown below.
<!-- 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-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
The AdMob App ID must be included in the AndroidManifest.xml
. Failure to do so will result in a crash on the launch of an app.
Initialize the Mobile Ads SDK
Before loading ads, have your app initialize the Mobile Ads SDK by calling MobileAds.instance.initialize()
which initializes the SDK and returns a Future
that finishes once initialization is complete (or after a 30-second timeout). This needs to be done only once, ideally right before running the app.
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
// Load ads.
}
}
Here is an Add a banner ad For all to see googleads-mobile-flutter
A BannerAd
requires an adUnitId, an AdSize, an AdRequest
, and an AdListener
. An example is shown below as well as more information on each parameter follows.
final BannerAd myBanner = BannerAd(
adUnitId: '<ad unit id>',
size: AdSize.banner,
request: AdRequest(),
listener: AdListener(),
);
To define a custom banner size, set your desired AdSize, as shown here:
final AdSize adSize = AdSize(300, 50);
Banner Ad Events
Through the use of AdListener
, you can listen for lifecycle events, such as when an ad is closed or the user leaves the app. This example implements each method and logs a message to the console:
final AdListener listener = AdListener(
// Called when an ad is successfully received.
onAdLoaded: (Ad ad) => print('Ad loaded.'),
// Called when an ad request failed.
onAdFailedToLoad: (Ad ad, LoadAdError error) {
print('Ad failed to load: $error');
},
// Called when an ad opens an overlay that covers the screen.
onAdOpened: (Ad ad) => print('Ad opened.'),
// Called when an ad removes an overlay that covers the screen.
onAdClosed: (Ad ad) => print('Ad closed.'),
// Called when an ad is in the process of leaving the application.
onApplicationExit: (Ad ad) => print('Left application.'),
);
After a BannerAd
is instantiated, load()
must be called before it can be shown on the screen.
myBanner.load();
To display a BannerAd
as a widget, you must instantiate an AdWidget
with a supported ad after calling load(). You can create the widget before calling load()
, but load()
must be called before adding it to the widget tree.
final AdWidget adWidget = AdWidget(ad: myBanner);
AdWidget
inherits from Flutter's Widget class and can be used as any other widget. On iOS, make sure you place the widget in a widget with a specified width and height. Otherwise, your Ad may not be displayed. A BannerAd
can be placed in a container with a size that matches the ad:
final Container adContainer = Container(
alignment: Alignment.center,
child: adWidget,
width: myBanner.size.width.toDouble(),
height: myBanner.size.height.toDouble(),
);
Finally, release the resource associated with the BannerAd object by calling the BannerAd.dispose()
method in the dispose()
callback method.
@override
void dispose() {
// TODO: Dispose BannerAd object
myBanner?.dispose();
super.dispose();
}
That's it! Your app is now ready to display banner ads.
Full Example
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp()));
}
// You can also test with your own ad unit IDs by registering your device as a
// test device. Check the logs for your device's ID value.
const String testDevice = 'YOUR_DEVICE_ID';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
BannerAd _bannerAd;
@override
void initState() {
super.initState();
_bannerAd = BannerAd(
adUnitId: BannerAd.testAdUnitId,
request: AdRequest(),
size: AdSize.banner,
listener: AdListener(
onAdLoaded: (Ad ad) {
print('$BannerAd loaded.');
},
onAdFailedToLoad: (Ad ad, LoadAdError error) {
print('$BannerAd failedToLoad: $error');
},
onAdOpened: (Ad ad) => print('$BannerAd onAdOpened.'),
onAdClosed: (Ad ad) => print('$BannerAd onAdClosed.'),
onApplicationExit: (Ad ad) => print('$BannerAd onApplicationExit.'),
),
);
_bannerAd?.load();
}
@override
void dispose() {
super.dispose();
_bannerAd?.dispose();
_bannerAd = null;
}
@override
Widget build(BuildContext context) {
final AdWidget adWidget = AdWidget(ad: _bannerAd);
return Scaffold(
appBar: AppBar(
title: const Text('Google Mobile Ads'),
actions: <Widget>[
],
),
body: Column(
children: [
Align(
alignment: FractionalOffset.topCenter,
child: Padding(
padding: EdgeInsets.only(top: 10.0),
child: Container(
alignment: Alignment.center,
child: adWidget,
width: _bannerAd.size.width.toDouble(),
height: _bannerAd.size.height.toDouble(),
)
),
)
],
),
);
}
}