简体   繁体   中英

How to integrate google mobile ads in flutter app

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

  1. Open the ios/Runner/Info.plist file in Android Studio.

  2. 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

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

  2. 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(),
                )
            ),
          )
        ],
      ),
    );
  }
}

在此处输入图像描述

Step 1: Add dependencies to pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2

  google_mobile_ads: ^0.13.0 #this

Step 2: Update your Info.plist in IOS and Update AndroidManifest.xml in Android

For IOS

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
<key>SKAdNetworkItems</key>
  <array>
    <dict>
      <key>SKAdNetworkIdentifier</key>
      <string>cstr6suwn9.skadnetwork</string>
    </dict>
  </array>

For Android

<manifest>
    <application>
        <!-- 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"/>
    </application>
</manifest>

Step 2:Initialize the Mobile Ads SDK in main.dart

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileAds.instance.initialize().then((InitializationStatus status) {
    print('Initialization done: ${status.adapterStatuses}');
    MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
          tagForChildDirectedTreatment:
              TagForChildDirectedTreatment.unspecified,
          testDeviceIds: <String>[]),//when you run first time you will get your test id in logs then update it here <String>["test id"]
    );
  });
  runApp(MyApp());
}

Step 4:Create Ad Units in Admob then we are ready to implement ads

Step 5:Make sure you enable multidex in app/build.gradle file

defaultConfig {
        ....
        multiDexEnabled true
    }

dependencies {
    ....
    implementation 'com.android.support:multidex:2.0.1'
}

Step 6: Create admanager.dart file

import 'package:google_mobile_ads/google_mobile_ads.dart';

AdRequest request = AdRequest(
  keywords: <String>[
    'foo',
    'bar',
    'wallpaper',
  ],
  contentUrl: 'URL',
  nonPersonalizedAds: true,
);

final BannerAd myBanner = BannerAd(
  adUnitId: 'ca-app-pub-3166882328175414/3480332744',
  size: AdSize.banner,
  request: request,
  listener: BannerAdListener(
        onAdLoaded: (Ad ad) {
          print('$BannerAd loaded.');
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('$BannerAd failedToLoad: $error');
          ad.dispose();
        },
        onAdOpened: (Ad ad) => print('$BannerAd onAdOpened.'),
        onAdClosed: (Ad ad) => print('$BannerAd onAdClosed.'),
      ),
);


final AdWidget adWidget = AdWidget(ad: myBanner);

Step 7: Now go to home page use it

import 'package:flutter/material.dart';
import 'package:vaccine/adManger.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    myBanner.load();
    super.initState();
  }

  final Container adContainer = Container(
    alignment: Alignment.center,
    child: adWidget,
    width: myBanner.size.width.toDouble(),
    height: myBanner.size.height.toDouble(),
  );

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [                        
                      adContainer,
                    ],
                  ),
               ),
            );
  }
}

Thanks

flutter 2.8 adding of Google Admobs

Add dependencies

google_mobile_ads: ^1.0.1

Import

import 'package:google_mobile_ads/google_mobile_ads.dart';

Go to android/local.properties and add versions

  • flutter.minSdkVersion=21
  • flutter.targetSdkVersion=30
  • flutter.compileSdkVersion=30

Goto android/app/build.gradle and add

-minSdkVersion localProperties.getProperty('flutter.minSdkVersion').toInteger()

-targetSdkVersion localProperties.getProperty('flutter.targetSdkVersion').toInteger()

Goto android/build.gradle

Update the Kotlin version

ext.kotlin_version = '1.6.0'

Once done follow the normal working of creating the adds

Good thing there is an existing documentation for Ads support for Flutter .

Monetizing apps by using ads has been one of the most popular requests for many Flutter developers.

Flutter ads support is available through the Google Mobile Ads SDK for Flutter (Beta) , which works with both AdMob and AdManager. This plugin supports a variety of ad formats, including banner (inline and overlay), interstitial, rewarded video, native ads, and adaptive banner.

在此处输入图像描述

The following video tutorial, Monetizing apps with Flutter , shows how to get started with Ads:

The following resources can help you get started:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM