question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

AdWidget stops camera preview on Android

See original GitHub issue

This plugin is currently useless due to this issue sadly if you want to show banner ads in a camera app.

Plugin Version

0.13.1

Steps to Reproduce

  1. Run flutter create bug.
  2. Add camera and google_mobile_ads to pubspec.yaml and run flutter pub get.
  3. Add the <meta-data ... /> tag to AndroidManifest.xml, following the instruction written in the README of this package.
  4. Paste the code below into main.dart and launch the app on an Android device by flutter run.
Code
import 'package:flutter/material.dart';

import 'package:camera/camera.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

late final List<CameraDescription> cameras;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  cameras = await availableCameras();

  runApp(const App());
}

class App extends StatefulWidget {
  const App();

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

class AppState extends State<App> {
  late final CameraController _controller;
  late final BannerAd _bannerAd;

  var _isAdReady = false;

  @override
  void initState() {
    super.initState();

    _controller = CameraController(cameras[0], ResolutionPreset.max)
      ..initialize().then((_) {
        if (mounted) {
          setState(() {});
        }
      });

    _loadBannerAd();
  }

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

  Future<void> _loadBannerAd() async {
    await MobileAds.instance.initialize();

    _bannerAd = BannerAd(
      size: AdSize.banner,
      request: const AdRequest(nonPersonalizedAds: false),
      adUnitId: 'ca-app-pub-3940256099942544/6300978111',
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          setState(() => _isAdReady = true);
        },
        onAdFailedToLoad: (ad, _) {
          _isAdReady = false;
          ad.dispose();
        },
      ),
    )..load();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Stack(
          children: [
            if (_controller.value.isInitialized) CameraPreview(_controller),
            if (_isAdReady)
              Align(
                alignment: Alignment.bottomCenter,
                child: SizedBox(
                  width: double.infinity,
                  height: _bannerAd.size.height.toDouble(),
                  child: AdWidget(ad: _bannerAd),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

Expected results:

The camera preview is not affected, whether a banner ad is being displayed or not.

Actual results:

The camera preview stops when a banner ad is shown. It starts again when the ad is removed.

Logs

flutter analyze

Analyzing ads_bug...
No issues found! (ran in 2.3s)

flutter doctor -v

[√] Flutter (Channel stable, 2.2.2, on Microsoft Windows [Version 10.0.19042.1055], locale ja-JP)
    • Flutter version 2.2.2 at D:\tool\dev\flutter
    • Framework revision d79295af24 (13 days ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at D:\tool\dev\Android\sdk
    • Platform android-30, build-tools 30.0.3
    • ANDROID_SDK_ROOT = D:\tool\dev\Android\sdk
    • Java binary at: D:\tool\dev\java\jdk8u292-b10\bin\java
    • Java version OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_292-b10)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.7.4)
    • Visual Studio at D:\tool\dev\Microsoft\Microsoft Visual Studio\2019\Community
    • Visual Studio Community 2019 version 16.7.30517.126
    • Windows 10 SDK version 10.0.18362.0

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).

[√] IntelliJ IDEA Ultimate Edition (version 2021.1)
    • IntelliJ at D:\tool\dev\JetBrains\apps\IDEA-U\ch-0\211.6693.111
    • Flutter plugin version 57.0.5
    • Dart plugin version 211.7233

[√] VS Code, 64-bit edition (version 1.56.2)
    • VS Code at C:\Program Files\Microsoft VS Code
    • Flutter extension version 3.23.0

[√] Connected device (3 available)
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [Version 10.0.19042.1055]
    • Chrome (web)      • chrome  • web-javascript • Google Chrome 91.0.4472.114
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 91.0.864.54

! Doctor found issues in 1 category.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:7

github_iconTop GitHub Comments

2reactions
maheshmnjcommented, Aug 31, 2021

Hi @kaboc, Thanks for filing the issue I am able to replicate the issue using the latest ads plugin 0.13.4 when the ad is added in the widget tree the camera freezes with a black screen and the ad loads, And removing the ads the app camera works fine.

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

import 'package:camera/camera.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

late final List<CameraDescription> cameras;
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(CameraApp());
}

class CameraApp extends StatefulWidget {
  CameraApp();

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

class CameraAppState extends State<CameraApp> {
  late final CameraController _controller;
  late final BannerAd _bannerAd;

  var _isAdReady = false;

  @override
  void initState() {
    super.initState();
    _loadBannerAd();
  }

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

  Future<void> _loadBannerAd() async {
    await MobileAds.instance.initialize();

    _bannerAd = BannerAd(
      size: AdSize.banner,
      request: const AdRequest(nonPersonalizedAds: false),
      adUnitId: 'ca-app-pub-3940256099942544/6300978111',
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          setState(() => _isAdReady = true);
        },
        onAdFailedToLoad: (ad, _) {
          _isAdReady = false;
          ad.dispose();
        },
      ),
    )..load();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Stack(
          children: [
            Column(
              children: const <Widget>[
                Expanded(child: Camera()),
              ],
            ),
            if (_isAdReady)
              Align(
                alignment: Alignment.bottomCenter,
                child: SizedBox(
                  width: double.infinity,
                  height: _bannerAd.size.height.toDouble(),
                  child: AdWidget(ad: _bannerAd),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

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

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

class _CameraState extends State<Camera> {
  late List<CameraDescription> _cameras;
  CameraController? _controller;

  initCameras() async {
    _cameras = await availableCameras();
    _controller = CameraController(_cameras[0], ResolutionPreset.medium);
    await _controller!.initialize();
    setState(() {});
  }

  @override
  void initState() {
    initCameras();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    if (_controller == null || !_controller!.value.isInitialized) {
      return const Center(
        child: Text(
          "Waiting for camera...",
          style: TextStyle(color: Colors.grey),
        ),
      );
    }
    return AspectRatio(
        aspectRatio: _controller!.value.aspectRatio,
        child: CameraPreview(_controller!));
  }
}

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 (9 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.25.0

[✓] Connected device (4 available)
    • Redmi K20 Pro (mobile) • d9dac45d                             • 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 92.0.4515.159

• No issues found!

This issue is potentially a duplicate of https://github.com/googleads/googleads-mobile-flutter/issues/32

2reactions
kaboccommented, Jun 24, 2021

This issue is gone if the plugin is replaced with a forked one written in another issue page. It appears that the fork uses AndroidView instead of PlatformViewLink.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Adwidget google_mobbile_ads flutter banner hangs camera ...
I am able to display the ad successfully, but the camera completely hangs(in emulator, oneplus5, samsung m31). In the emulator, I am unable...
Read more >
Camera preview | Android Developers
Multi-window mode constrains camera apps to a portion of the screen, scaling the camera preview regardless of device orientation. Multi-display ...
Read more >
Add widgets on iPhone - Apple Support
To view widgets, swipe right from the left edge of the Home Screen or the Lock Screen, then scroll up ... When you...
Read more >
How to Use Google Photos Memories Widget on Android and ...
Google Photos memories widget lets you see old photos on your phone's home screen. Here's how to use the widget on Android and...
Read more >
Not able to see widgets on OnePlus 8t after updating to ...
After updating my op8t to Android 12 based stable oxygen os I'm not able to find ... Im also facing this issue.. but...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found