Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Android] BannerAd is right aligned on some devices #261

Closed
pixelgroup-israel opened this issue Jun 2, 2021 · 21 comments
Closed

[Android] BannerAd is right aligned on some devices #261

pixelgroup-israel opened this issue Jun 2, 2021 · 21 comments
Assignees
Labels
banner ad Issues related to Banner Ad platform-android Android applications specifically

Comments

@pixelgroup-israel
Copy link

Plugin Version

0.13.0

Steps to Reproduce

I have implemented adWidget in the following format:

final Container adContainer = Container(
    color: Colors.red,
    constraints: BoxConstraints(
        minHeight: myBanner.sizes.first.height.toDouble() + 10,
    ),
    child: Column(
        children: [
            Flex(
                direction: Axis.horizontal,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                    Container(
                        color: Colors.green,
                        width: myBanner.sizes.first.width.toDouble(),
                        height: myBanner.sizes.first.height.toDouble(),
                        alignment: Alignment.center,
                        child: AdWidget(
                            ad: myBanner,
                        ),
                    )
                ],
            ),
        ],
    ),
);

Expected results:

Ad should be centered and should cover the green rectangle.

Actual results:

Ad is aligned to the right of the screen.

photo_2021-06-02 08 55 53

@maheshj01 maheshj01 added the in triage Issue currently being evaluated label Aug 6, 2021
@maheshj01
Copy link
Collaborator

@pixelgroup-israel thanks for filing the issue. Could you please share the output of flutter doctor -v and a minimal complete reproducible code. I have attached a code sample below which shows a banner shown in a container in the center of the screen.

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

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

class BannerApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: CenteredBanner());
  }
}

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

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

class _CenteredBannerState extends State<CenteredBanner> {
  late BannerAd _bannerAd;
  bool isAdloaded = false;
  @override
  void initState() {
    super.initState();
    _bannerAd = BannerAd(
      adUnitId: BannerAd.testAdUnitId,
      size: AdSize.mediumRectangle,
      request: AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) {
          print('$BannerAd loaded.');
          setState(() {
            isAdloaded = true;
          });
        },
      ),
    );
    _bannerAd.load();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Banner Ad')),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            color: Colors.blue,
            alignment: Alignment.center,
            child: SizedBox(
              width: _bannerAd.size.width.toDouble(),
              height: _bannerAd.size.height.toDouble(),
              child: AdWidget(ad: _bannerAd),
            ),
          ),
        ],
      ),
    );
  }
}
output
flutter doctor -v
[✓] Flutter (Channel stable, 2.2.3, on macOS 11.4 20F71 darwin-arm, locale en-GB)
    • Flutter version 2.2.3 at /Users/mahesh/Documents/flutter
    • Framework revision f4abaa0735 (4 weeks ago), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/mahesh/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /Users/mahesh/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.4, Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] IntelliJ IDEA Community Edition (version 2021.1.2)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin version 57.0.5
    • Dart plugin version 211.7233

[✓] VS Code (version 1.58.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.24.0

[✓] Connected device (4 available)
    • Redmi K20 Pro (mobile)     • 192.168.1.3:5555                     • android-arm64  • Android 11 (API 30)
    • iPhone 12 Pro Max (mobile) • 6A434744-B348-4FB3-AB10-131292174456 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
    • macOS (desktop)            • macos                                • darwin-arm64   • macOS 11.4 20F71 darwin-arm
    • Chrome (web)               • chrome                               • web-javascript • Google Chrome 92.0.4515.107

• No issues found!

Let me know if I am missing anything.

Thank you.

@maheshj01 maheshj01 added the feedback required Further information is requested label Aug 6, 2021
@morio77
Copy link

morio77 commented Sep 6, 2021

me too.

@maheshj01
Copy link
Collaborator

@morio77 could you provide more info on the issue and possibly a minimal code sample.

Thanks

@morio77
Copy link

morio77 commented Sep 6, 2021

@maheshmnj Here is the code.

return Scaffold(
            appBar: AppBar(),
            body: Center(
              child: Column(
                children: [
                  Container(),
                  Container(),
                  ),
                ],
              ),
            ),
            // Bottom(バナー広告)
            bottomNavigationBar: const SafeArea(
              child: AdBanner(size: AdSize.fullBanner),
              left: true,
              right: true,
              bottom: true,
            ),
          );
class AdBanner extends StatelessWidget {
  const AdBanner({
    required this.size, // サイズは利用時に指定
  });
  final AdSize size;
  Widget build(BuildContext context) {
    final banner = BannerAd(
        size: size,
        adUnitId: BannerAd.testAdUnitId,
        listener: AdManagerBannerAdListener(
          onAdLoaded: (Ad ad) => print('Ad loaded.'),
          onAdFailedToLoad: (Ad ad, LoadAdError error) {
            print('Ad failed to load: $error');
          },
          onAdOpened: (Ad ad) => print('Ad opened.'),
          onAdClosed: (Ad ad) => print('Ad closed.'),
        ),
        // リクエストはデフォルトを使う
        request: const AdRequest())
      // 表示を行うloadをつける
      ..load();

    // 戻り値はContainerで包んで返す
    return Container(
      alignment: Alignment.center,
      width: banner.size.width.toDouble(),
      height: banner.size.height.toDouble(),
      child: SizedBox(
        child: AdWidget(ad: banner),
      ),
    );
  }

  // 広告IDをプラットフォームに合わせて取得
  static String get bannerAdUnitId {
    if (Platform.isAndroid) {
      return "XXX";
    } else if (Platform.isIOS) {
      return "YYY";
    } else {
      //どちらでもない場合は、テスト用を返す
      return BannerAd.testAdUnitId;
    }
  }
}

@morio77
Copy link

morio77 commented Sep 6, 2021

@maheshmnj

The image is part of the app. The advertisement may shift in this way.
Android only.

スクリーンショット 2021-09-10 23 20 39

@maheshj01
Copy link
Collaborator

@mario77 what is your expected output? As per your code your output is correct also note that you are trying to show a fullsized banner

AdBanner(size: AdSize.fullBanner),

so it will cover the full width regardless of whatever alignment you pass to the banner.

@morio77
Copy link

morio77 commented Sep 7, 2021

@maheshmnj

The ads seem to have shifted to the right overall.

The expected output is that there is no black area on the left and the YouTube logo on the right is all visible.

@maheshj01
Copy link
Collaborator

maheshj01 commented Sep 7, 2021

@morio77 thanks for the clarification, I am able to reproduce the issue this issue is mainly on Android, The ads are shifted to right

AdBanner(size: AdSize.fullBanner),
Android IOS
flutter doctor -v
[✓] Flutter (Channel stable, 2.2.3, on macOS 11.5.2 20G95 darwin-arm, locale en-GB)
    • Flutter version 2.2.3 at /Users/mahesh/Documents/flutter
    • Framework revision f4abaa0735 (10 weeks ago), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/mahesh/Library/Android/sdk
    • Platform android-31, build-tools 31.0.0
    • ANDROID_HOME = /Users/mahesh/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.59.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.26.0

[✓] Connected device (4 available)
    • Redmi K20 Pro (mobile) • 192.168.1.4:5555                     • android-arm64  • Android 11 (API 30)
    • iPhone 12 Pro (mobile) • B622CBB7-F906-4FA7-8F49-FACEAAC905AB • ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-5
      (simulator)
    • macOS (desktop)        • macos                                • darwin-arm64   • macOS 11.5.2 20G95 darwin-arm
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 93.0.4577.63

• No issues found!

@maheshj01 maheshj01 added bug Something isn't working e2-days Effort: < 5 days p1-high platform-android Android applications specifically and removed feedback required Further information is requested in triage Issue currently being evaluated labels Sep 7, 2021
@maheshj01 maheshj01 added the banner ad Issues related to Banner Ad label Nov 2, 2021
@maheshj01 maheshj01 changed the title Can't align banner to the center of the container [Android] BannerAd is right aligned on some devices Nov 2, 2021
@maheshj01
Copy link
Collaborator

cc: @jjliu15

@mustafa-707
Copy link

mustafa-707 commented Nov 8, 2021

same here
flutter 2.5.3
google_mobile_ads: ^0.13.6

devices :
Huawei P30 lite
and
Xiaomi note 10s lite

@mustafa-707
Copy link

mustafa-707 commented Feb 2, 2022

@jjliu15 @maheshmnj

any updates on that , still happens on [google_mobile_ads] v 1.0.1 and flutter 2.8.1 stable

@maheshj01
Copy link
Collaborator

Unfortunately no update so far, Please keep an eye on this issue for future updates.

@mustafa-707
Copy link

same using flutter 3.0.1 stable and google_mobile_ads v 1.2.0

@timothyhoang-google
Copy link
Collaborator

We're looking into this issue.

@jjliu15
Copy link
Collaborator

jjliu15 commented Sep 28, 2022

This appears to be happening when the size of the rendered ad does not match the AdSize that was requested.

For example, in #261 (comment) the size requested was fullBanner, but the image shows a 320x50 ad (most likely because 468 is too wide for the device). We make the ad container width 468, which looks nicer on iOS than Android, probably due to different default layout constraints.

I think generally we need a better way to handle the case where the returned banner ad size does not match the requested size. Maybe something similar to FluidAdWidget or with different constraints.

@blueeyestw
Copy link

blueeyestw commented Oct 27, 2022

Hi, for those facing the same issue:

According to the official Android Docs

螢幕擷取畫面 2022-10-27 140909

However, for us Flutter developers, the banner ad always appears even if you define AdSize as greater than your container's width. This is what I think is causing the issue we are facing. Also note that AdSize.fullBanner and AdSize.leaderboard are exclusively used for tablet-sized screens since an iPhone 14 Pro Max (probably the largest phone) only has a width of 430.

In short:

  1. Don't use AdSize.fullBanner and AdSize.leaderboard unless you plan to properly support tablets and foldables.
  2. If you want to support all screen sizes, then use the code below:
import 'dart:developer';
import 'dart:io';

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

class BannerAdContainer extends StatefulWidget {
  const BannerAdContainer({super.key});

  @override
  State<BannerAdContainer> createState() => _BannerAdContainerState();
}

class _BannerAdContainerState extends State<BannerAdContainer> {
  BannerAd? bannerAd;
  Container adContainer = Container();

  @override
  void didChangeDependencies() {
    double width = MediaQuery.of(context).size.width;
    loadBannerAd(width);
    super.didChangeDependencies();
  }

  void loadBannerAd(double width) async {
    String adUnitId = '';
    AdSize adSize = AdSize.banner;
    if (width >= 468) adSize = AdSize.fullBanner;
    if (width >= 728) adSize = AdSize.leaderboard;
    if (!kReleaseMode) {
      if (Platform.isAndroid) {
        adUnitId = 'ca-app-pub-3940256099942544/6300978111'; //official android debug banner ad unit id
      } else if (Platform.isIOS) {
        adUnitId = 'ca-app-pub-3940256099942544/2934735716'; //official iOS debug banner ad unit id
      }
    } else {
      if (Platform.isAndroid) {
        adUnitId = ''; //TODO enter your own Android Ad Unit ID
      } else if (Platform.isIOS) {
        adUnitId = ''; //TODO enter your own iOS Ad Unit ID
      }
    }
    if (adUnitId.isNotEmpty) {
      bannerAd = BannerAd(
        adUnitId: adUnitId,
        size: adSize,
        request: const AdRequest(),
        listener: BannerAdListener(
          onAdLoaded: (ad) => log('ad loaded'),
          onAdFailedToLoad: (ad, error) {
            log('ad failed to load: $error');
            destroyBannerAd();
            if (mounted) setState(() {});
          },
          onAdClicked: (ad) => log('ad clicked'),
          onAdOpened: (ad) => log('ad opened'),
          onAdClosed: (ad) => log('ad closed'),
        ),
      );
      await bannerAd?.load();
      if (bannerAd != null) {
        final AdWidget adWidget = AdWidget(ad: bannerAd!);
        log('ad width: ${bannerAd!.size.width}');
        log('ad hieght: ${bannerAd!.size.height}');
        adContainer = Container(
          alignment: Alignment.center,
          width: bannerAd!.size.width.toDouble(),
          height: bannerAd!.size.height.toDouble(),
          child: adWidget,
        );
        if (mounted) setState(() {});
      }
    }
  }

  void destroyBannerAd() {
    adContainer = Container();
    bannerAd?.dispose();
    bannerAd = null;
  }

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

  @override
  Widget build(BuildContext context) {
    return adContainer;
  }
}

mobile

@huycozy
Copy link
Collaborator

huycozy commented Jul 20, 2023

We’re closing this issue due to inactivity. If you’re still impacted, please create a new issue via the Developer Forum.

@huycozy huycozy closed this as not planned Won't fix, can't repro, duplicate, stale Jul 20, 2023
@patolax
Copy link

patolax commented Oct 9, 2023

I have created a new bug for this. please fix it.
#928 (comment)

And this is the response from the developer forum after a few weeks.
image

@huycozy
Copy link
Collaborator

huycozy commented Oct 11, 2023

Re-open this issue as there is a similar report recently #928.

@huycozy huycozy reopened this Oct 11, 2023
@patolax
Copy link

patolax commented Oct 11, 2023

I have tried several Google forums to get this fixed or obtain a proper implementation method.

This is the last response I got. Not sure where to go from here.
image

I can't release the app ads shown like this. It looks horrible.
image

This is my test device https://www.motorola.com.au/smartphone-motorola-moto-g22/p.
On this device, other admob apps are working fine. Including the android example apps for admob.

This is my code. Please provide me with a working solution.


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

  @override
  State<AdBanner> createState() => _AdBannerState();
}

class _AdBannerState extends State<AdBanner> {
  BannerAd? _inlineAdaptiveAd;
  bool _isLoaded = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      var windowwidth = MediaQuery.of(context).size.width.truncate();
      _loadAd(windowwidth);
    });
  }

  void _loadAd(int windowwidth) async {
    await _inlineAdaptiveAd?.dispose();
    // Get an inline adaptive size for the current orientation.
    AdSize size = AdSize.banner;
    size = (await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
        windowwidth)) as AdSize;

    _inlineAdaptiveAd = BannerAd(
      adUnitId: AdHelper.bannerAdUnitId,
      size: size,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) async {
          debugPrint('Inline BannerAdListener onAdLoaded');
          if (mounted) {
            setState(() {
              _isLoaded = true;
            });
          }
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          debugPrint('Inline adaptive banner failedToLoad: $error');
          _isLoaded = false;
          ad.dispose();
        },
      ),
    );
    await _inlineAdaptiveAd!.load();
  }

  @override
  Widget build(BuildContext context) {
    return (_isLoaded && _inlineAdaptiveAd != null)
        ? Align(
            alignment: Alignment.bottomCenter,
            child: SizedBox(
                width: _inlineAdaptiveAd!.size.width.toDouble(),
                height: _inlineAdaptiveAd!.size.height.toDouble(),
                child: AdWidget(
                  ad: _inlineAdaptiveAd!,
                )))
        : const SizedBox(
            width: 0,
            height: 0,
          );
  }

  @override
  void dispose() {
    _inlineAdaptiveAd?.dispose();

    super.dispose();
  }
}

@malandr2
Copy link
Collaborator

@patolax per the documentation, you should be calling getPlatformAdSize() in the onAdLoaded callback to get the updated platform ad size and update the AdWidget container height.

Please take a look at the code example in docs and see if the code provided can be used to resolve your issue. Thanks.

@malandr2 malandr2 closed this as completed Mar 4, 2024
@malandr2 malandr2 removed bug Something isn't working p1-high e2-days Effort: < 5 days labels Mar 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
banner ad Issues related to Banner Ad platform-android Android applications specifically
Projects
None yet
Development

No branches or pull requests

10 participants