Implement Collapsible Banner AdMob in Flutter

Do you know about Collapsible Banner AdMob? A new ad format is introduced by Google AdMob. In this article, we will see how to implement collapsible banner ads in your Flutter project. Basically, this kind of ad will help you to increase your or client revenue.

collapsible banner admob, collapsible banner ads flutter, collapsible banner admob test id, collapsible banner admob github, collapsible banner admob flutter, collapsible banner admob policy, collapsible banner AdMob iOS, collapsible banner admob android, collapsible banner ads, collapsible banner admob example, collapsible banner android

 

 

Admob is a popular platform for displaying different kinds of ads. You can integrate banner, interstitial, app open, rewarded, and native ads by using admob in your Flutter project. A collapsible banner ad loads with expanded mode. It displays with larger overlay content. A collapse button that allows the user to collapse it back to its original banner size. It helps to maintain a clear interface while implementing it in your project.

How to Integrate Collapsible Banner AdMob in Flutter

Implementing a collapsible banner admob in Flutter is very simple. We will see a step-by-step guide below:

Step 1: Create a new Project
  1. Open Android Studio.
  2. Click on New Flutter Project.
  3. Make sure you have selected your Flutter SDK Path. Click Next
  4. Enter the Project Name, Project Location (where you need to put the project),
  5. Select the project type (Default Application).
  6. Enter Organization
  7. Select Android and iOS languages (default: Kotlin and Swift).
  8. Select Platforms (On which platform you want to run the project).
  9. Click on Finish button.
  10. Now wait for the project to finish building.
Step 2: Adding the Mobile Ads Package in the pubspec.yaml
  • Open the pubspec.yaml file from the left panel of the project directory.
  • Add the google_mobile_ads package under dependencies.
google_mobile_ads: ^5.1.0
  • Click on Pub get to retrieve packages in the project.
Step 3: Modify AndroidManifest.xml
  • Add test AdMob AppId to your in AndroidManifest file by adding the <meta-data> tag inside the <application> tag
<manifest> 
          <application> 
                      <meta-data
                               android:name="com.google.android.gms.ads.APPLICATION_ID"
                               android:value="ca-app-pub-3940256099942544~3347511713" />
          </application> 
</manifest>
Step 4: Implement code to display collapsible banner ads.
  • initialize the Mobile Ads SDK in main.dart file
void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
runApp(const MyApp());
}
  • Import google_mobile_ads package on top.
import 'package:google_mobile_ads/google_mobile_ads.dart';
  • Create adRequest object.
static const adRequest = AdRequest(extras: {
"collapsible": "bottom",
});

There are two types of placement values. (1) top (2) bottom

(1) top: The top of the expanded ad aligns to the top of the collapsed ad.

(2) bottom: The bottom of the expanded ad aligns to the bottom of the collapsed ad.

  • Create a banner object. Initialize _currentOrientation and _isLoaded variables.
BannerAd? _bannerAd;
bool _isLoaded = false;
Orientation? _currentOrientation;
  • Call the _loadAd() method to setup banner ad from the initState() method.
@override
void initState() {
// TODO: implement initState
super.initState();
_loadAd();
}
Step 5: Implement full code to display collapsible banner admob ads in the main.dart file.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Collapsible Banner Ads',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Collapsible Banner Ads'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const adRequest = AdRequest(extras: {
    "collapsible": "bottom",
  });

  BannerAd? _bannerAd;
  bool _isLoaded = false;
  Orientation? _currentOrientation;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _loadAd();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            backgroundColor: Colors.blue,
            title: Text(widget.title),
            centerTitle: true,
            foregroundColor: Colors.white),
        body: OrientationBuilder(
          builder: (context, orientation) {
            if (_currentOrientation != orientation) {
              _isLoaded = false;
              _loadAd();
              _currentOrientation = orientation;
            }
            return Stack(
              children: [
                if (_bannerAd != null && _isLoaded)
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: SafeArea(
                      child: SizedBox(
                        width: _bannerAd!.size.width.toDouble(),
                        height: _bannerAd!.size.height.toDouble(),
                        child: AdWidget(ad: _bannerAd!),
                      ),
                    ),
                  )
              ],
            );
          },
        ));
  }

  void _loadAd() async {
    // Get an AnchoredAdaptiveBannerAdSize before loading the ad.
    final size = await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
        MediaQuery.sizeOf(context).width.truncate());

    if (size == null) {
      // Unable to get width of anchored banner.
      return;
    }

    BannerAd(
      adUnitId: Platform.isAndroid
          ? 'ca-app-pub-3940256099942544/2014213617'
          : 'ca-app-pub-3940256099942544/8388050270', //collapsible banner admob test id
      request: adRequest,
      size: size,
      listener: BannerAdListener(
        // Called when an ad is successfully received.
        onAdLoaded: (ad) {
          setState(() {
            _bannerAd = ad as BannerAd;
            _isLoaded = true;
          });
        },
        // Called when an ad request failed.
        onAdFailedToLoad: (ad, err) {
          ad.dispose();
        },
        // Called when an ad opens an overlay that covers the screen.
        onAdOpened: (Ad ad) {},
        // Called when an ad removes an overlay that covers the screen.
        onAdClosed: (Ad ad) {},
        // Called when an impression occurs on the ad.
        onAdImpression: (Ad ad) {},
      ),
    ).load();
  }
}
Step 6: All set! Run the project. See the screenshots of collapsible banner ads below.

Android:

collapsible banner admob, collapsible banner ads flutter, collapsible banner admob test id, collapsible banner admob github, collapsible banner admob flutter, collapsible banner admob policy, collapsible banner AdMob iOS, collapsible banner admob android, collapsible banner ads, collapsible banner admob example, collapsible banner android

 

 

 

iOS Setup:

  • Add Admob App ID in the info.plist file. Locate this file with the below steps:
  • ios > Runner > info.plist
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>

info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>$(DEVELOPMENT_LANGUAGE)</string>
	<key>CFBundleDisplayName</key>
	<string>Collapsible Ads</string>
	<key>CFBundleExecutable</key>
	<string>$(EXECUTABLE_NAME)</string>
	<key>CFBundleIdentifier</key>
	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>collapsible_ads</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>$(FLUTTER_BUILD_NAME)</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleVersion</key>
	<string>$(FLUTTER_BUILD_NUMBER)</string>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>UILaunchStoryboardName</key>
	<string>LaunchScreen</string>
	<key>UIMainStoryboardFile</key>
	<string>Main</string>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UISupportedInterfaceOrientations~ipad</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationPortraitUpsideDown</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>CADisableMinimumFrameDurationOnPhone</key>
	<true/>
	<key>UIApplicationSupportsIndirectInputEvents</key>
	<true/>
	<key>GADApplicationIdentifier</key>
        <string>ca-app-pub-3940256099942544~1458002511</string>
</dict>
</plist>

 

iOS Output:

 

Implement Collapsible Banner AdMob in Flutter
collapsible banner admob, collapsible banner ads flutter, collapsible banner admob test id, collapsible banner admob github, collapsible banner admob flutter, collapsible banner admob policy, collapsible banner AdMob iOS, collapsible banner admob android, collapsible banner ads, collapsible banner admob example, collapsible banner android

 

Conclusion

A Collapsible Banner AdMob Ads is easy to use in the flutter. It improves user interaction seamlessly. It allows the user to collapse the larger layout to back the banner size. Users may engage more with ads that don’t interfere with their experience. It also generates more revenue than other ad formats of banner ads.

Frequently Asked Questions(FAQs)

What are the different types of banners in AdMob?

Anchored adaptive, inline adaptive, and collapsible are formats of banner ads in the AdMob.

What are mobile banner ads?

A mobile banner ad is a rectangular display ad unit. It can be either animated or static. This ad generally displays on the top or bottom of the screen. It automatically refreshes after a certain period of time.

What is better than banner ads?

Rewarded ads are better than banner ads. Rewarded video or interstitial ads are high rpm over all other ad formats in AdMob.

Leave a comment