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

Screenshot package stops working when using Google Ads #729

Closed
chinmaysarupria opened this issue Dec 17, 2022 · 7 comments
Closed

Screenshot package stops working when using Google Ads #729

chinmaysarupria opened this issue Dec 17, 2022 · 7 comments
Labels
banner ad Issues related to Banner Ad bug Something isn't working e4-months Effort: 1+ months p2-medium

Comments

@chinmaysarupria
Copy link

I have an app in which I have integrated google ads as well as screenshot package to allow users to share a screenshot of a particular widget. Both packages independently work well. But screenshot package stops working if google ads are used.

In screenshot package, one has to wrap any widget with screenshot controller and needs to call capture method on this controller to generate an image or a snapshot of that widget which can then be shared. But load method on BannerAd class is blocking image generation on screenshot package.

Here is my code:

  BannerAd? _bannerAd;

  void _init() {
   // Set up banner ad 
   // _bannerAd = ...

      _bannerAd!.load(); // This is the line causing issues
    }
  }

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

If I comment out this load method, then the screenshot works fine. Here is the code for screenshot package:

Future<void> _shareScreenshot(BuildContext context) async {
    double pixelRatio = MediaQuery.of(context).devicePixelRatio;
    await controller!
        .capture(
      delay: const Duration(milliseconds: 10),
      pixelRatio: pixelRatio,
    )
        .then(
      (Uint8List? image) async {
        if (image != null) { // This if block will trigger if there is no load method on banner ad
          final directory = await getApplicationDocumentsDirectory();
          final imagePath = await File('${directory.path}/image.png').create();
          await imagePath.writeAsBytes(image);

          await Share.shareFiles([imagePath.path],
              text: 'Some text');
        } else { // Else gets triggered if load is used
          print('Image is null');
        }
      },
    );
  }

Plugin Version

2.3.0

Steps to Reproduce

Integrate

Expected results: Google ads and screenshot working fine

Actual results: Google ads load method breaking something on screenshot package

@huycozy huycozy added the in triage Issue currently being evaluated label Dec 19, 2022
@huycozy
Copy link
Collaborator

huycozy commented Dec 19, 2022

Hi @chinmaysarupria
To be more precise, please provide the information indicated below:

Thank you!

@huycozy huycozy added the feedback required Further information is requested label Dec 19, 2022
@chinmaysarupria
Copy link
Author

Hi @huycozy

Here are the details:

  • A github repo with a reproducible sample: ads_screenshot
  • Tested on Android, never tried on iOS
  • Output of flutter doctor -v:
[✓] Flutter (Channel stable, 3.3.10, on macOS 12.1 21C52 darwin-arm, locale
    en-IN)
    • Flutter version 3.3.10 on channel stable at
      /Users/chinmaysarupria/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 135454af32 (5 days ago), 2022-12-15 07:36:55 -0800
    • Engine revision 3316dd8728
    • Dart version 2.18.6
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/chinmaysarupria/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13F100
    • CocoaPods version 1.11.3

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

[✓] Android Studio (version 2021.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.12+0-b1504.28-7817840)

[✓] VS Code (version 1.74.1)
    • VS Code at /Applications/Visual Studio Code 2.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (3 available)
    • IN2011 (mobile) • 522b454a • android-arm64  • Android 12 (API 31)
    • macOS (desktop) • macos    • darwin-arm64   • macOS 12.1 21C52 darwin-arm
    • Chrome (web)    • chrome   • web-javascript • Google Chrome 108.0.5359.98

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

I am unable to post output of flutter run -v as it is huge and Github is not allowing to post such large text.

@github-actions github-actions bot removed the feedback required Further information is requested label Dec 20, 2022
@huycozy
Copy link
Collaborator

huycozy commented Dec 21, 2022

@chinmaysarupria thanks for providing sample code but it doesn't work even with simple Container as below modified sample code:

Sample code
import 'dart:typed_data';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance..initialize()..updateRequestConfiguration(
      RequestConfiguration(
        testDeviceIds: <String>[
          '20FB23B5E117EC42488FBC0A024F306F',
        ],
      )
  );
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: const HomeScreen(),
    );
  }
}

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Future<void> _shareScreenshot(
      BuildContext context, ScreenshotController controller) async {
    double pixelRatio = MediaQuery.of(context).devicePixelRatio;
    await controller
        .capture(
      delay: const Duration(milliseconds: 10),
      pixelRatio: pixelRatio,
    )
        .then(
      (Uint8List? image) async {
        if (image != null) {
          final directory = await getApplicationDocumentsDirectory();
          final imagePath = await File('${directory.path}/image.png').create();
          await imagePath.writeAsBytes(image);

          await Share.shareFiles([imagePath.path]);
        }
      },
    );
  }

  bool _isBannerAdReady = false;
  BannerAd? _bannerAd;

  @override
  void initState() {
    super.initState();
    _bannerAd = BannerAd(
      adUnitId: 'ca-app-pub-3940256099942544/6300978111', // test banner id
      size: AdSize.banner,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (ad) => setState(() {
          _isBannerAdReady = true;
        }),
        onAdFailedToLoad: (ad, error) {
          _isBannerAdReady = false;
          ad.dispose();
        },
      ),
    );

    // If load method is commented out then screenshot package will start working again
    _bannerAd!.load();
  }

  @override
  Widget build(BuildContext context) {
    final ScreenshotController screenshotController = ScreenshotController();
    return Scaffold(
      appBar: AppBar(
        title: const Text('Ads + Screenshot'),
        actions: [
          InkWell(
            onTap: () => _shareScreenshot(context, screenshotController),
            child: const Padding(
              padding: EdgeInsets.all(16.0),
              child: Icon(Icons.share),
            ),
          ),
        ],
      ),
      body: Stack(
        children: [
          SizedBox(
            width: double.infinity,
            child: Screenshot(
              controller: screenshotController,
              child: Card(
                margin: const EdgeInsets.all(32.0),
                child: Padding(
                  padding: const EdgeInsets.all(32.0),
                  child: Column(
                    children: const [
                      Text('Ads + Screenshot'),
                    ],
                  ),
                ),
              ),
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              color: Colors.red,
              width: double.maxFinite,
              height: 32,
            ),
          ),

          // if (_isBannerAdReady)
          //   Align(
          //     alignment: Alignment.bottomCenter,
          //     child: SizedBox(
          //       width: _bannerAd!.size.width.toDouble(),
          //       height: _bannerAd!.size.height.toDouble(),
          //       child: AdWidget(ad: _bannerAd!),
          //     ),
          //   ),
        ],
      ),
    );
  }
}

Please double-check your implementation. In case it's screenshot package issue, please file a new issue in that repository for better support.

@huycozy huycozy added the feedback required Further information is requested label Dec 21, 2022
@chinmaysarupria
Copy link
Author

@huycozy Yes, it will not work as the load method is being called. I had also added a comment just above it that if load method is commented out screenshot will work and if it is not then screenshot will stop working.

_bannerAd!.load(); // Simply comment out this line and your code will also start working

@github-actions github-actions bot removed the feedback required Further information is requested label Dec 21, 2022
@huycozy
Copy link
Collaborator

huycozy commented Dec 22, 2022

@chinmaysarupria I can reproduce this issue on both Android and iOS when running your sample code at ads_screenshot. When commenting out _bannerAd!.load(), the screenshot function works as normal.

Labeling the issue for further insights from the team. Thank you!

@huycozy huycozy added bug Something isn't working p2-medium e4-months Effort: 1+ months banner ad Issues related to Banner Ad dependencies Pull requests that update a dependency file and removed in triage Issue currently being evaluated dependencies Pull requests that update a dependency file labels Dec 22, 2022
@chinmaysarupria
Copy link
Author

@huycozy I was trying a few things to see if it can be resolved. This is what I did: in my code, I was initializing screenshot controller in build method.

Widget build(BuildContext context) {
    final ScreenshotController screenshotController = ScreenshotController();
    ...
}

I moved it outside build method to see what happens:

final ScreenshotController screenshotController = ScreenshotController();

Widget build(BuildContext context) {
    ...
}

and the issue got resolved. Screenshots started working again. I still do not know why it is working this way but this is what I found:

  • As long as ads load method is not used, screenshot controller can be defined anywhere - inside or outside build method.
  • But if load method is called, screenshot controller has to be defined outside of the build method only.

@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
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 bug Something isn't working e4-months Effort: 1+ months p2-medium
Projects
None yet
Development

No branches or pull requests

2 participants