GithubHelp home page GithubHelp logo

bdlukaa / native_admob_flutter Goto Github PK

View Code? Open in Web Editor NEW
80.0 5.0 55.0 33.05 MB

Easy-to-make native ads in flutter using AdMOB SDK.

Home Page: https://pub.dev/packages/native_admob_flutter

License: BSD 3-Clause "New" or "Revised" License

Kotlin 19.48% Swift 21.97% Objective-C 0.01% Dart 57.73% Ruby 0.80%
native-ads admob flutter dart android admob-sdk

native_admob_flutter's Introduction

native_admob_flutter

Easy-to-make ads in Flutter with Google's AdMob SDK.\ English | [Português](README-PT.md)

⚠️ Deprecated

The project is now archived. Reasons are documented below:

  • Flutter Platform Views: This plugin will never be good enough if the flutter platform views don't work correctly: Virtual Display (AndroidView) should work fine, but the gestures are mapped and performed progamatically, which isn't allowed by the admob policy and can make your account be banned. Hybrid Composition, on the other hand, is unperformatic, buggy and can let to several crashes (by 03/2022) - see open issues. I know that several improvements are being done to Hybrid Composition, but it's currently not usable in production;
  • Google Mobile Ads: This plugin uses the same native implementation (Hybrid Composition) as google_mobile_ads - the ads plugin maintained by the Google Ads Team themselves -, which I believe they'll be able to maintain it better than me;
  • Poor iOS support: (#58) I don't have a macOS to be able to develop for iOS. All the current iOS implementation was done by the community itself. Hybrid Composition on iOS has the same issue as on Android - see open issues - as well, which makes your app unusable.

Get started

To get started with Native Ads for Flutter, read the documentation

✔️ Native Ads (Android-only)
✔️ Banner Ads
✔️ Interstitial Ads
✔️ Rewarded Ads
✔️ App Open Ads
✔️ Rewarded Intersitital Ads

AdMOB only supports ads on mobile. Web and desktop are out of reach

✔️ Android
✔️ iOS (Huge thanks to @clemortel)

Issues and feedback

Please file issues, bugs, or feature requests in our issue tracker.

To contribute a change to this plugin open a pull request.

native_admob_flutter's People

Contributors

bdlukaa avatar clemortel avatar mozerrr avatar ramtinq avatar sageata avatar skyost avatar yusriltakeuchi avatar zhengbomo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

native_admob_flutter's Issues

Banner ad loads and disappear( triggers loadFailed event) and always shows real ads

Hi.

I've been trying to implement this package, but im facing some weird behaviour.

1st: Banner ads reloads every x time.

This is the code i have:

class SymbolsPage extends StatefulWidget {
  @override
  _SymbolsPageState createState() => _SymbolsPageState();
}



class _SymbolsPageState extends State<SymbolsPage> {
  final hc = Get.put(HomeController());

  final ac = Get.find<AdmobController>();

  final TextEditingController nameController = TextEditingController();

  Logger logger = Logger();

  final bannerController = BannerAdController();


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

     bannerController.onEvent.listen((e) {
      final event = e.keys.first;
      switch (event) {
        case BannerAdEvent.loading:
          logger.i('BannerAdEvent: loading');
          break;
        case BannerAdEvent.loaded:
          logger.i('BannerAdEvent: loaded');
          break;
        case BannerAdEvent.loadFailed:
          final errorCode = e.values.first;
          logger.i('BannerAdEvent: loadFailed $errorCode');
          break;
        case BannerAdEvent.impression:
          logger.i('BannerAdEvent: ad rendered');
          break;
        default:
          break;
      }
  });
    
  }

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

  }

  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.yellow[800],
      appBar: AppBar(
        title: Text('name'),
        backgroundColor: appThemeData.primaryColor,
      ),
      body: GetBuilder<HomeController>(
        builder: (_) => Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 30, left: 18, right: 18),
              child: CustomSearchText(
                text: hc.nickName,
                enable: true,
                callback: () {
                  nameController.text = hc.nickName;
                  TextSelection.fromPosition(
                    TextPosition(offset: nameController.text.length),
                  );
                  // TODO: Fix bug when generating new nickname and does not change in textbox if focus is on
                },
                controller: nameController,
                callback2: (text) {
                  TextSelection previousSelection = nameController.selection;
             
                  nameController.selection = previousSelection;
                  logger.v("${nameController.selection.start}");
                  _.changeNickName(text);
                },
              ),
            ),

        
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
            
                FlatButton.icon(
                  icon: Icon(Icons.copy_rounded),
                  label: Text('copy'.tr),
                  color: appThemeData.accentColor,
                  onPressed: () {
                    Clipboard.setData(ClipboardData(text: hc.nickName));
                    Get.snackbar("snackbar_download_title".tr,
                        "snackbar_download_message".tr,
                        snackPosition: SnackPosition.BOTTOM,
                        backgroundColor: appThemeData.accentColor);
                  },
                )
              ],
            ),
            const SizedBox(
              height: 10,
            ),
          
            Expanded(
              child: GridView.builder(
                  padding: EdgeInsets.only(left: 8, right: 8),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    childAspectRatio: 3 / 2,
                    crossAxisSpacing: 20,
                    mainAxisSpacing: 20,
                    crossAxisCount: 4,
                  ),
                  itemCount: symbols2.length,
                  itemBuilder: (BuildContext ctx, index) {
                    return GestureDetector(
                      onTap: () {
                     
                        Get.snackbar("snackbar_download_title2".tr,
                            "snackbar_download_message".tr,
                            snackPosition: SnackPosition.BOTTOM,
                            backgroundColor: appThemeData.accentColor);
                        print("nameController.selection.start");
                        Clipboard.setData(
                            ClipboardData(text: symbols2[index].symbol));
                      },
                      child: Container(
                        alignment: Alignment.center,
                        child: Text(symbols2[index].symbol),
                        decoration: BoxDecoration(
                            color: appThemeData.accentColor,
                            borderRadius: BorderRadius.circular(15)),
                      ),
                    );
                  }),
            ),

            
             BannerAd(controller: bannerController, size: BannerSize.ADAPTIVE),
          ],
        ),
      ),
      bottomNavigationBar: BottomBar(),
    );
  }
}

adchanges
adchanges2

2nd: Ads are loaded as production ads or test ads(like random), even though i hardcoded them or, in this case, i retrieve them from my "MyAdmob.class" or wether i place them in the initialize method or straight in the widget's parameter the result is the same.

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await MobileAds.initialize(
    bannerAdUnitId: MyAdmob.getBannerAdId(),
    interstitialAdUnitId: MyAdmob.getInterstitialAdId(),
    appOpenAdUnitId: MyAdmob.getOpenAdId(),
    
  );
  Get.put(AdmobController());
  // FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
  // Admob.requestTrackingAuthorization();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  // Locale myLocale;

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'names',
      debugShowCheckedModeBanner: false,
      theme: appThemeData,
      translations: MyTransalations(),
      locale: Get.deviceLocale,
      home: SplashPage(),
      // locale: Get.deviceLocale,
      // translations: MyTransalations(),
    );
  }
}

IOS IDFA: Unsupported value: __C.ATTrackingManagerAuthorizationStatus of type __SwiftValue

If I add final TrackingAuthorizationStatus status = await MobileAds.requestTrackingAuthorization();
my app will crash

This is the crash log

`Unsupported value: __C.ATTrackingManagerAuthorizationStatus of type __SwiftValue
*** Assertion failure in -[FlutterStandardWriter writeValue:], FlutterStandardCodec.mm:330
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unsupported value for standard codec'
*** First throw call stack:
(0x18f18d86c 0x1a41a8c50 0x18f093000 0x19042791c 0x103f43098 0x103f4010c 0x103057fe8 0x103076954 0x103076a00 0x1c11fbb7c 0x1030762f0 0x103076bf8 0x103f40074 0x1036dfb78 0x1039def5c 0x10397e35c 0x103980a14 0x18f109fa0 0x18f109ba0 0x18f108ffc 0x18f102ee4 0x18f10221c 0x1a6cce784 0x191b42ee8 0x191b4875c 0x102e58378 0x18edc26b0)
libc++abi.dylib: terminating with uncaught exception of type NSException

  • thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
    frame #0: 0x00000001bd0e2414 libsystem_kernel.dylib__pthread_kill + 8 libsystem_kernel.dylib__pthread_kill:
    -> 0x1bd0e2414 <+8>: b.lo 0x1bd0e2434 ; <+40>
    0x1bd0e2418 <+12>: pacibsp
    0x1bd0e241c <+16>: stp x29, x30, [sp, #-0x10]!
    0x1bd0e2420 <+20>: mov x29, sp
    Target 0: (Runner) stopped.
    `

native ads are crashing app on loading

hello guys i am app
i use native ads but now its was crashing

plz help me guys

my :: pubspec.yaml

description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  connectivity: ^3.0.3
  
  native_admob_flutter: ^1.2.4
  # admob_flutter: ^1.0.1
  
  intl: ^0.17.0
  shared_preferences: ^2.0.5
  
  
  # flutter_spinkit: ^4.1.2old
  
  # fluttertoast: ^8.0.3
  fluttertoast: ^7.1.8
  flutter_inappwebview: ^5.2.1+1
  # flutter_inappwebview: ^4.0.0+4 old
  # webview_flutter: ^1.0.7
  
  #state management
  get: ^4.1.4
  get_storage: ^2.0.2
 

  # downloader --
  path_provider: ^2.0.1
  #old  path_provider: ^1.6.27
  # flutter_downloader: ^1.5.2
  flutter_downloader: ^1.6.0
  permission_handler: ^6.1.1
  # permission_handler: ^6.0.1+1 old


  # authentication--
  firebase_auth: ^1.0.1
  # oldgoogle_sign_in: ^4.5.3
  google_sign_in: ^5.0.1
  provider: ^5.0.0
  
  cloud_firestore: ^1.0.3
  # firebase_core : ^1.0.0 old
  firebase_core: ^1.0.2
  firebase_crashlytics: ^1.0.0
  #ui designe
  # flutter_native_splash:
  shimmer: ^1.1.2
  lottie:
  flutter_gradients:
  carousel_pro: ^1.0.0
  flutter_spinkit: ^5.0.0
  animated_widgets: ^1.0.6
  flutter_svg: ^0.19.3
  adobe_xd: ^1.1.0+1
  
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
 

dev_dependencies:
  flutter_launcher_icons: ^0.8.0
  #change_app_package_name: ^0.1.2
  flutter_native_splash: 
  flutter_test:
    sdk: flutter
flutter_icons:
  
  android: true
  ios: true
  image_path: "assets/bluebook.png"

flutter_native_splash:

  # This package generates native code to customize Flutter's default white native splash screen
  # with background color and splash image.
  # Customize the parameters below, and run the following command in the terminal:
  # flutter pub run flutter_native_splash:create
  # To restore Flutter's default white splash screen, run the following command in the terminal:
  # flutter pub run flutter_native_splash:remove

  # color or background_image is the only required parameter.  Use color to set the background
  # of your splash screen to a solid color.  Use background_image to set the background of your
  # splash screen to a png image.  This is useful for gradients. The image will be stretch to the
  # size of the app. Only one parameter can be used, color and background_image cannot both be set.
  # color: "#42a5f5"
  color: "#FFFFFF"
  #background_image: "assets/background.png"
  
  # Optional parameters are listed below.  To enable a parameter, uncomment the line by removing 
  # the leading # character.

  # The image parameter allows you to specify an image used in the splash screen.  It must be a 
  # png file.  
  image: assets/bluebook.png

  # The color_dark, background_image_dark, and image_dark are parameters that set the background
  # and image when the device is in dark mode. If they are not specified, the app will use the
  # parameters from above. If the image_dark parameter is specified, color_dark or 
  # background_image_dark must be specified.  color_dark and background_image_dark cannot both be
  # set.
  #color_dark: "#042a49"
  #background_image_dark: "assets/dark-background.png"
  #image_dark: assets/splash-invert.png

  # The android, ios and web parameters can be used to disable generating a splash screen on a given 
  # platform.
  android: true
  ios: false
  web: false

  # The position of the splash image can be set with android_gravity, ios_content_mode, and
  # web_image_mode parameters.  All default to center.
  #
  # android_gravity can be one of the following Android Gravity (see 
  # https://developer.android.com/reference/android/view/Gravity): bottom, center, 
  # center_horizontal, center_vertical, clip_horizontal, clip_vertical, end, fill, fill_horizontal,
  # fill_vertical, left, right, start, or top.
  android_gravity: center
  #
  # ios_content_mode can be one of the following iOS UIView.ContentMode (see 
  # https://developer.apple.com/documentation/uikit/uiview/contentmode): scaleToFill, 
  # scaleAspectFit, scaleAspectFill, center, top, bottom, left, right, topLeft, topRight, 
  # bottomLeft, or bottomRight.
  #ios_content_mode: center
  #
  # web_image_mode can be one of the following modes: center, contain, stretch, and cover.
  #web_image_mode: center

  # To hide the notification bar, use the fullscreen parameter.  Has no affect in web since web 
  # has no notification bar.  Defaults to false.
  # NOTE: Unlike Android, iOS will not automatically show the notification bar when the app loads.
  #       To show the notification bar, add the following code to your Flutter app:
  #       WidgetsFlutterBinding.ensureInitialized();
  #       SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom, SystemUiOverlay.top]);
  fullscreen: true
  
  # If you have changed the name(s) of your info.plist file(s), you can specify the filename(s) 
  # with the info_plist_files parameter.  Remove only the # characters in the three lines below,
  # do not remove any spaces:
  #info_plist_files:
  #  - 'ios/Runner/Info-Debug.plist'
  #  - 'ios/Runner/Info-Release.plist'


# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  
  assets:
   - assets/anna.jpg
   - assets/014-girl-13.svg
   - assets/004-notebook.svg
   - assets/006-school.svg
   - assets/calculator.png
   - assets/calculator.svg
   - assets/score.svg
   - assets/trophy.svg
   - assets/certification.svg
   - assets/student.svg
   - assets/ece.png
   - assets/bluebook.png
   - assets/bg1.png
   - assets/tech.json
   - assets/code.json
   - assets/gift.json
   - assets/teaching.json
   - assets/developer.png
   - assets/loading.json
   - assets/server-error.json
   - assets/page-error.json
   - assets/images/ex1.png
   - assets/nointernet.json
   - assets/no-internet-connection.json
   - assets/editnointernet.json
   - assets/nointernetout.json


  
  
  
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

my code:

import 'package:au_updates/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:au_updates/screen/settings.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_gradients/flutter_gradients.dart';

import 'package:au_updates/calculator/Courses/IT.dart';
import 'package:au_updates/calculator/Courses/Mech.dart';
import 'package:au_updates/calculator/Courses/Civil.dart';
import 'package:au_updates/calculator/Courses/Eee.dart';
import 'package:au_updates/calculator/Courses/Bme.dart';
import 'package:au_updates/calculator/Courses/cse.dart';
import 'package:au_updates/calculator/Courses/ece.dart';
import 'package:lottie/lottie.dart';
import 'package:native_admob_flutter/native_admob_flutter.dart';

class Gpapage extends StatefulWidget {
  @override
  _GpapageState createState() => _GpapageState();
}

String router1;
String router2;
String _valuedept = "Select Department";

class _GpapageState extends State<Gpapage> {
  final interstitialAd = InterstitialAd();
//unitId: initalunit()
  List<String> deptments = [
    "ECE",
    "EEE",
    "CSE",
    "IT",
    "BME",
    "MECH",
    "CIVIL",
    "Select Department",
  ];
  @override
  void initState() {
    if (!interstitialAd.isLoaded) interstitialAd.load();
    interstitialAd.onEvent.listen((e) {
      final event = e.keys.first;
      switch (event) {
        case FullScreenAdEvent.closed:
          // Here is a handy place to load a new interstitial after displaying the previous one
          interstitialAd.load();
          // Do not show an ad here
          break;
        default:
          break;
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: appbarcolour,
        title: Text(
          'Anna University GPA Calculator',
          style: TextStyle(
              fontSize: 21,
              fontWeight: FontWeight.bold,
              color: appbartextcolour),
          textAlign: TextAlign.center,
        ),
        elevation: 01,
      ),
      body: SafeArea(
        child: Container(
          decoration: BoxDecoration(gradient: FlutterGradients.newYork()),
          child: Center(
            child: Column(children: <Widget>[
              SizedBox(
                height: 2,
              ),
              // Container(
              //   height: 150,
              //   child: imageCarousel(context, adsenable: true),
              // ),
              Expanded(
                child: Container(
                  height: 200,
                  child: NativeAd(
                    builder: (context, child) {
                      return Container(
                        child: child,
                      );
                    },
                    buildLayout: adbuilder,
                    loading: Lottie.asset("assets/loading.json"),
                    error: Lottie.asset("assets/page-error.json"),
                    //Text('Error in ADs Server \n Please report to developer'),
                    icon: AdImageView(size: 100, padding: EdgeInsets.all(5)),
                    ratingBar: AdRatingBarView(
                        elevationColor: Colors.white, height: 20),
                    store: AdTextView(
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.normal,
                        color: Colors.amber[300],
                      ),
                    ),
                    button: AdButtonView(
                      pressColor: Colors.white,
                      padding: EdgeInsets.all(10),
                      textStyle: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Colors.black54,
                          letterSpacing: 0.3),
                    ),
                    headline: AdTextView(
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                      maxLines: 1,
                    ),
                    media: AdMediaView(height: 80, width: 120),
                  ),
                ),
              ),




AdLayoutBuilder get adbuilder => (ratingBar, media, icon, headline, advertiser,
        body, price, store, attribution, button) {
      return AdLinearLayout(
        gravity: LayoutGravity.center,
        padding: EdgeInsets.all(10),
        // The first linear layout width needs to be extended to the
        // parents height, otherwise the children won't fit good
        height: MATCH_PARENT,
        width: MATCH_PARENT,
        orientation: HORIZONTAL,
        decoration: AdDecoration(
          gradient: AdRadialGradient(
            colors: [Colors.blue, Colors.blue],
            center: Alignment(0.5, 0.5),
            radius: 1000,
          ),
        ),

        children: [
          icon,
          AdLinearLayout(
            gravity: LayoutGravity.left,
            padding: EdgeInsets.fromLTRB(20, 0, 0, 0),
            // height: 0.5,
            children: [
              headline,
              AdLinearLayout(
                gravity: LayoutGravity.left,
                padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
                children: [
                  attribution,
                  AdLinearLayout(
                    gravity: LayoutGravity.left,
                    padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                    children: [
                      ratingBar,
                      advertiser,
                      AdLinearLayout(
                        gravity: LayoutGravity.left,
                        padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                        children: [store],
                        orientation: HORIZONTAL,
                        width: WRAP_CONTENT,
                      ),
                    ],
                    orientation: HORIZONTAL,
                    width: WRAP_CONTENT,
                  ),
                ],
                orientation: HORIZONTAL,
                width: WRAP_CONTENT,
              ),
              AdLinearLayout(
                gravity: LayoutGravity.left,
                padding: EdgeInsets.fromLTRB(0, 10, 10, 3),
                children: [
                  button,
                ],
                width: 230,
              ),
            ],
            margin: EdgeInsets.all(5),
          ),
        ],
      );

error log on visual code :

D/EgretLoader(15947): EgretLoader(Context context)
D/EgretLoader(15947): The context is not activity
I/DynamiteModule(15947): Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:210890500
I/DynamiteModule(15947): Selected remote version of com.google.android.gms.ads.dynamite, version >= 210890500
2
W/ResourceType(15947): No package identifier when getting name for resource number 0x00000000
W/ResourceType(15947): ResTable_typeSpec entry count inconsistent: given 67, previously 69
W/ResourceType(15947): ResTable_typeSpec entry count inconsistent: given 5625, previously 5626
D/DynamitePackage(15947): Instantiating com.google.android.gms.ads.ChimeraNativeAdViewDelegateCreatorImpl
I/zygote64(15947): Do full code cache collection, code=250KB, data=165KB
I/zygote64(15947): After code cache collection, code=242KB, data=132KB
I/zygote64(15947): Do partial code cache collection, code=249KB, data=135KB
I/zygote64(15947): After code cache collection, code=249KB, data=135KB
I/zygote64(15947): Increasing code cache capacity to 1024KB
D/TransportRuntime.SQLiteEventStore(15947): Storing event with priority=HIGHEST, name=FIREBASE_CRASHLYTICS_REPORT for destination cct
D/TransportRuntime.JobInfoScheduler(15947): Scheduling upload for context TransportContext(cct, HIGHEST, MSRodHRwczovL2NyYXNobHl0aWNzcmVwb3J0cy1wYS5nb29nbGVhcGlzLmNvbS92MS9maXJlbG9nL2xlZ2FjeS9iYXRjaGxvZ1xBSXphU3lCcnBTWVQ0RkZMMDlyZUhKaTZIOUZZZGVpU25VVE92Mk0=) with jobId=372847150 in 20117ms(Backend next call timestamp 1619615312293). Attempt 1

error for firebase Crashlytics :

       at com.bruno.native_admob_flutter.native.NativeAdKt.applyText(NativeAd.kt:338)
       at com.bruno.native_admob_flutter.native.NativeAdPlatformView.buildView(NativeAd.kt:85)
       at com.bruno.native_admob_flutter.native.NativeAdPlatformView.buildView(NativeAd.kt:81)
       at com.bruno.native_admob_flutter.native.NativeAdPlatformView.buildView(NativeAd.kt:81)
       at com.bruno.native_admob_flutter.native.NativeAdPlatformView.build(NativeAd.kt:52)
       at com.bruno.native_admob_flutter.native.NativeAdPlatformView.<init>(NativeAd.kt:235)
       at com.bruno.native_admob_flutter.native.NativeViewFactory.create(NativeAd.kt:30)
       at io.flutter.plugin.platform.SingleViewPresentation.onCreate(SingleViewPresentation.java:186)
       at android.app.Dialog.dispatchOnCreate(Dialog.java:403)
       at android.app.Dialog.show(Dialog.java:302)
       at android.app.Presentation.show(Presentation.java:249)
       at io.flutter.plugin.platform.VirtualDisplayController.<init>(VirtualDisplayController.java:95)
       at io.flutter.plugin.platform.VirtualDisplayController.create(VirtualDisplayController.java:48)
       at io.flutter.plugin.platform.PlatformViewsController$1.createVirtualDisplayForPlatformView(PlatformViewsController.java:207)
       at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.create(PlatformViewsChannel.java:104)
       at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.onMethodCall(PlatformViewsChannel.java:59)
       at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
       at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
       at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:331)
       at android.os.Looper.loop(Looper.java:149)
       at android.app.ActivityThread.main(ActivityThread.java:6635)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

right open app ad implementation

Hi Guys,

Im quite new in flutter and Android development and not sure if I understand right way how to implement app-open-ads. If I understand well, app open ads only show when users foreground my app. According documentation, you always call await appOpenAd.show() for showing open ad. Can you please provide example how to achieve in flutter to show open ad when app goes to foreground?

This controller has already been attached to a native or banner ad.You need one controller for each

Every time this error is showing when I close the screen.
I tried by putting banner controller and also native ad controller to banner and native ads.
I tried putting controller as well as not putting controller always this error is showing?

I/flutter (30214): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (30214): The following assertion was thrown while finalizing the widget tree:
I/flutter (30214): This controller has already been attached to a native or banner ad.You need one controller for each
I/flutter (30214): 'package:native_admob_flutter/src/utils.dart':
I/flutter (30214): Failed assertion: line 214 pos 7: '!attached'
I/flutter (30214):
I/flutter (30214): When the exception was thrown, this was the stack:

Code:

      bottomNavigationBar: NativeAd(
          controller: _nativAdController,
          height: 60,
          buildLayout: adBannerLayoutBuilder,
          loading: Text('Loading'),
          error: Text('Error'),
          icon: AdImageView(padding: EdgeInsets.only(left: 6)),
          headline: AdTextView(
            style: TextStyle(color: Colors.black),
            maxLines: 1,
          ),
          advertiser: AdTextView(style: TextStyle(color: Colors.black)),
          body: AdTextView(style: TextStyle(color: Colors.black)),
          media: AdMediaView(height: 70, width: 120),
          button: AdButtonView(
            margin: EdgeInsets.only(left: 6, right: 6),
            textStyle: TextStyle(color: Colors.green, fontSize: 14),
          ),
        ),

I am getting initization error

Hey there, I am using Adaptive banner into my widget tree without defining any controller. And I am getting below error message-

Unhandled Exception: 'package:native_admob_flutter/src/utils.dart': Failed assertion: line 34 pos 5: 'MobileAds.isInitialized': The Mobile Ads SDK must be initialized before any ads can be loaded

1.0.0-pre.1 - Android is the only supported platform for now

I'm using 1.0.0-pre.1 and I keep getting this error when trying to run on an iPhone. Even that I intend to use BannerAds on iOS for now.

[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: 'package:native_admob_flutter/src/utils.dart': Failed assertion: line 23 pos 10: 'Platform.isAndroid': Android is the only supported platform for now
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
#2      assertPlatformIsSupported (package:native_admob_flutter/src/utils.dart:23:10)
#3      MobileAds.initialize (package:native_admob_flutter/src/mobile_ads.dart:113:5)
#4      main (package:blitzcoin/main.dart:31:19)
#5      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:140:25)
#6      _rootRun (dart:async/zone.dart:1354:13)
#7      _CustomZone.run (dart:async/zone.dart:1258:19)
#8      _runZoned (dart:async/zone.dart:1788:10)
#9      runZonedGuarded (dart:async/zone.dart:1776:12)
#10     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:133:5)
#11     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
#12     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

[FEATURE REQUEST] enable reading Ad content (headline, body, icon, etc.) of NativeAd to be readable from NativeAdController

I was hoping if you could implement some getter methods for NativeAdController which return details of the loaded NativeAd. This would be helpful for creating placeholder widgets for our NativeAds so that whenever we are animating them, we'd show the placeholder instead to overcome the issue of low performance in animations

This specifically could be useful in iOS as mentioned in #31 (comment) where the performance impact is high.

It has benefits for both platforms since we can show THE REAL NativeAd only when the user can interact with it and show the placeholder in the rest of situations.

interstitial in portrait orientation showing landscape Interstitial.

is it anyway to define the interstitial ads orientation ? Interstitial seems to be showing only landscape Interstitial forever even in portrait orientation.

this happen only if the interstitial display (once) in landscape mode and future intestinal will be landscape mode.

iOS implementation requires Android embedding v2

Trying to run on an iOS 14 device, I receive the following message:

The plugin native_admob_flutter requires your app to be migrated to the Android embedding v2. Follow the steps on https://flutter.dev/go/android-project-migration and re-run this command. Exited (1)

If this package supports both Android and iOS, why do I need to include Android embedding support?
Is this something that will change as the package matures?

IOS build errors

The build fails for me on IOS with the build errors like these below. I have tried, cleaning but it doesn't help. Any suggestions?

Error output from Xcode build:

/.pub-cache/hosted/pub.dartlang.org/native_admob_flutter-1.2.0/ios/Classes/Interstitial/InterstitialAdController.swift:5:25: error: cannot find type 'GADInterstitialAd' in scope
pub.dartlang.org/native_admob_flutter-1.2.0/ios/Classes/Interstitial/InterstitialAdController.swift:29:13: error: cannot find 'GADInterstitialAd' in scope
.pub-cache/hosted/pub.dartlang.org/native_admob_flutter-1.2.0/ios/Classes/Interstitial/InterstitialAdController.swift:29:83: error: cannot find type 'GADInterstitialAd' in scope
.pub-cache/hosted/pub.dartlang.org/native_admob_flutter-1.2.0/ios/Classes/Native/NativeAdController.swift:4:37: error: cannot find type 'GADNativeAdLoaderDelegate' in scope
.pub-cache/hosted/pub.dartlang.org/native_admob_flutter-1.2.0/ios/Classes/Native/NativeAdController.swift:45:27: error: value of type 'GADNativeAd' has no member 'muteThisAd'
.pub-cache/hosted/pub.dartlang.org/native_admob_flutter-1.2.0/ios/Classes/Native/NativeAdView.swift:222:41: error: value of type 'GADNativeAd' has no member 'starRating'

iOS support (beta)

The iOS support is almost done. The example app is running, and ads are working

You can try it by using the version 1.0.0-pre.1:

dependencies:
  native_admob_flutter: 1.0.0-pre.1

MobileAds

  • .initialize
  • UNSUPORTTED .isTestDevice
  • .setTestDeviceIds
  • .setChildDirected
  • .setTagForUnderAgeOfConsent
  • .setMaxAdContentRating
  • .setAppVolume
  • .setAppMuted
  • .requestTrackingAuthorization

Full screen ads

Method Interstitial Rewarded App Open
.load ✔️ ✔️ ✔️
.show ✔️ ✔️ ✔️

Platform view ads

Method Native Ad Banner Ad
.load ✔️ ✔️
Add to the tree ✔️ ✔️

Native Ads is not stable yet!

iOS support is still in beta and was not widely tested! You may find some issues when using it

Huge thanks to. They're the reason this is happening:

Version solving failed error

Hi, I'm trying to use the latest version of this package (1.1.0) because it has the requestTrackingAuthorization method and has a bunch of bug fixes, however, I am getting this error:

pub get failed (1; Because my_app requires SDK version >=2.12.0 <3.0.0, version solving failed.)
exit code 1

I think this error is happening because my project does not support null safety. I don't want to use the version without null safety (0.9.4) though since it doesn't have the requestTrackingAuthorization method nor the bug fixes. So what can I do?

real ads are not loading error :3 but test ads are working fine

**Main dart**

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileAds.initialize(
      // nativeAdUnitId: "xxxxxxx",
      interstitialAdUnitId: "xxxxxx");

  MobileAds.setTestDeviceIds(['xxxxxxx']);
  //Admob.initialize();
  await Firebase.initializeApp();
  await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;

  await FlutterDownloader.initialize(
      // debug: true // optional: set false to disable printing logs to console
      );
  await Permission.storage.request();

  runZoned(() {
    runApp(Appui());
  });
}



**my ads page code :::::**

 final interstitialAd =
      InterstitialAd(unitId: "ca-app-pub-2820502455308437/3641680546");

 @override
  void initState() {
    if (!interstitialAd.isLoaded) interstitialAd.load();
    interstitialAd.onEvent.listen((e) {
      final event = e.keys.first;
      switch (event) {
        case FullScreenAdEvent.closed:
          // Here is a handy place to load a new interstitial after displaying the previous one
          interstitialAd.load();
          // Do not show an ad here
          break;
        default:
          break;
      }
    });
    super.initState();
  }


**show ads** 
  IconButton(
                icon: Icon(Icons.ac_unit),
                onPressed: () async {
                  if (interstitialAd.isLoaded) {
                    await interstitialAd.show();
                  } else {
                    await interstitialAd.load();
                  }
                },
              ),

and native ads also same 


**error ::**

D/DynamitePackage( 7730): Instantiating com.google.android.gms.ads.ChimeraAdManagerCreatorImpl
I/Ads     ( 7730): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("02A6AAB51B2AB59A326BCEA37FF7306A")) to get test ads on this device.
I/DynamiteModule( 7730): Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:210402101
I/DynamiteModule( 7730): Selected remote version of com.google.android.gms.ads.dynamite, version >= 210402101
I/DynamiteModule( 7730): Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:210402101
I/DynamiteModule( 7730): Selected remote version of com.google.android.gms.ads.dynamite, version >= 210402101
2
D/AudioManager( 7730): getStreamVolume isRestricted mode = 0
I/Ads     ( 7730): Ad failed to load : 3

Plugin crashes on iOS 14.5 with Fatal error: Float value cannot be converted to Int

Swift/x86_64-apple-ios-simulator.swiftinterface:32532: Fatal error: Float value cannot be converted to Int because it is either infinite or NaN

I call (initalize in main.dart, the getBannerAd() in the relevant widget)

MobileAds.initialize(bannerAdUnitId: MobileAds.bannerAdTestUnitId);

    Widget getBannerAd() => BannerAd(
          size: BannerSize.ADAPTIVE,
          error: Container(),
        );

iOS banner ad errors

Hello, when I run my app with banner ads on a physical iOS device I get the following errors:

Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
WF: _userSettingsForUser mobile: {
    filterBlacklist =     (
    );
    filterWhitelist =     (
    );
    restrictWeb = 1;
    useContentFilter = 0;
    useContentFilterOverrides = 0;
    whitelistEnabled = 0;
}
WF: _WebFilterIsActive returning: NO

Code:

OrientationBuilder(
  builder: (BuildContext context,
      Orientation orientation) {
    if (orientation != oldOrientation) {
      bannerAdController.load(force: true);
      WidgetsBinding.instance!
          .addPostFrameCallback((_) {
        setState(() {
          oldOrientation = orientation;
        });
      });
    }
    return Align(
      alignment: Alignment.bottomCenter,
      child: BannerAd(
        controller: bannerAdController,
        builder: (context, child) {
          return Container(
            child: child,
            color: Theme.of(context).primaryColor,
          );
        },
        loading: Container(
          width:
              MediaQuery.of(context).size.width,
          height: _bannerAdHeight,
          color: Theme.of(context).primaryColor,
        ),
        error: Container(),
        size: BannerSize.ADAPTIVE,
        nonPersonalizedAds: true,
        unitId: AdHelper.bannerAd,
      ),
    );
  },
);

The ad still shows up and works even though I'm receiving this error.

The required version to use the AdMOB SDK is 16 or higher

Using the latest version and getting this error

I/flutter ( 8746): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter ( 8746): The following assertion was thrown building NativeAd(dirty, state: _NativeAdState#1861b): I/flutter ( 8746): The required version to use the AdMOB SDK is 16 or higher I/flutter ( 8746): 'package:native_admob_flutter/src/utils.dart': I/flutter ( 8746): Failed assertion: line 47 pos 7: 'MobileAds.osVersion >= 16' I/flutter ( 8746): I/flutter ( 8746): The relevant error-causing widget was: I/flutter ( 8746): NativeAd I/flutter ( 8746): lib/…/main/main.screen.dart:226 I/flutter ( 8746): I/flutter ( 8746): When the exception was thrown, this was the stack: I/flutter ( 8746): #2 assertVersionIsSupported package:native_admob_flutter/src/utils.dart:47 I/flutter ( 8746): #3 _NativeAdState.build package:native_admob_flutter/…/native/native_ad_widget.dart:219 I/flutter ( 8746): #4 StatefulElement.build package:flutter/…/widgets/framework.dart:4744 I/flutter ( 8746): #5 ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:4627 I/flutter ( 8746): #6 StatefulElement.performRebuild package:flutter/…/widgets/framework.dart:4800 I/flutter ( 8746): #7 Element.rebuild package:flutter/…/widgets/framework.dart:4343 I/flutter ( 8746): #8 ComponentElement._firstBuild package:flutter/…/widgets/framework.dart:4606 I/flutter ( 8746): #9 StatefulElement._firstBuild package:flutter/…/widgets/framework.dart:4791 I/flutter ( 8746): #10 ComponentElement.mount package:flutter/…/widgets/framework.dart:4601 I/flutter ( 8746): ... Normal element mounting (13 frames) I/flutter ( 8746): #23 Element.inflateWidget package:flutter/…/widgets/framework.dart:3569 I/flutter ( 8746): #24 MultiChildRenderObjectElement.mount package:flutter/…/widgets/framework.dart:6236 I/flutter ( 8746): ... Normal element mounting (91 frames) I/flutter ( 8746): #115 Element.inflateWidget package:flutter/…/widgets/framework.dart:3569 I/flutter ( 8746): #116 Element.updateChild package:flutter/…/widgets/framework.dart:3324 I/flutter ( 8746): #117 ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:4652 I/flutter ( 8746): #118 StatefulElement.performRebuild package:flutter/…/widgets/framework.dart:4800 I/flutter ( 8746): #119 Element.rebuild package:flutter/…/widgets/framework.dart:4343 I/flutter ( 8746): #120 BuildOwner.buildScope package:flutter/…/widgets/framework.dart:2730 I/flutter ( 8746): #121 WidgetsBinding.drawFrame package:flutter/…/widgets/binding.dart:913 I/flutter ( 8746): #122 RendererBinding._handlePersistentFrameCallback package:flutter/…/rendering/binding.dart:302 I/flutter ( 8746): #123 SchedulerBinding._invokeFrameCallback package:flutter/…/scheduler/binding.dart:1117 I/flutter ( 8746): #124 SchedulerBinding.handleDrawFrame package:flutter/…/scheduler/binding.dart:1055 I/flutter ( 8746): #125 SchedulerBinding._handleDrawFrame package:flutter/…/scheduler/binding.dart:971 I/flutter ( 8746): #129 _invoke (dart:ui/hooks.dart:251:10) I/flutter ( 8746): #130 _drawFrame (dart:ui/hooks.dart:209:3) I/flutter ( 8746): (elided 5 frames from class _AssertionError and dart:async) I/flutter ( 8746): I/flutter ( 8746): ════════════════════════════════════════════════════════════════════════════════════════════════════

I guess the logic here supposed to be the opposite?

/// Assert the current version is supported.
/// The min versions are:
///  - iOS: 9
///  - Android: 16 (19 for Native and Banner Ads)
void assertVersionIsSupported([bool usePlatformView = true]) {
  if (Platform.isAndroid) {
    /// The min required version for Android is 16
    assert(
      MobileAds.osVersion >= 16,
      'The required version to use the AdMOB SDK is 16 or higher',
    );

    /// The required version by flutter to use PlatformViews is
    ///   - Hybrid composition: 19
    ///   - Virtual display: 20
    if (usePlatformView)
      assert(
        MobileAds.osVersion >= 19,
        'Native and Banner Ads are not supported in versions before 19 because'
        ' flutter only support platform views on Android 19 or greater.',
      );
  } else {
    /// The min required version for iOS is 9
    assert(
      MobileAds.osVersion >= 9,
      'The required version to use the AdMOB SDK is 9 or higher',
    );
  }
}

Not all asset views lie inside the native ad view

Hi.

Please help. I've been trying to implement this package (native_admob_flutter: ^1.2.0) and running on an emulator, but I'm facing some weird log message:

I/Ads ( 6336): Received log message: Google:HTML Native ad view size has been detected to be 360x10. This size seems to be too small, and might indicate a problem with your SDK implementation. Note that ad slots that have a width or height smaller than 32 will be demonetized in the future. Please make sure the ad view has sufficiently large area.

I/Ads ( 6336): Received log message: Google:HTML Not all asset views lie inside the native ad view. This indicates an integration problem. Such implementations will not be supported in the future. Please make sure that all native ad assets are rendered inside the native ad view.

This is the code i have:

AdLayoutBuilder get adDefaultLayoutBuilder => (ratingBar, media, icon, headline,
    advertiser, body, price, store, attribution, button) {
  return AdLinearLayout(
    decoration: AdDecoration(backgroundColor: Color(0xFF111111)),
    width: MATCH_PARENT,
    height: MATCH_PARENT,
    orientation: HORIZONTAL,
    gravity: LayoutGravity.center_vertical,
    children: [
      //icon,
      AdLinearLayout(
        children: [icon],
        orientation: HORIZONTAL,
        width: WRAP_CONTENT,
        margin: EdgeInsets.symmetric(horizontal: 3),
      ),
      AdExpanded(
        flex: 2,
        child: AdLinearLayout(
          width: WRAP_CONTENT,
          margin: EdgeInsets.symmetric(horizontal: 3),
          children: [
            headline,
            AdLinearLayout(
              orientation: HORIZONTAL,
              children: [attribution, advertiser],
            ),
          ],
        ),
      ),
      AdExpanded(flex: 4, child: button),
    ],
  );
};
          bottomNavigationBar: Container(
            width: MediaQuery.of(context).size.width,
            color: primaryColor,
            height: _isBannerAdReady ? 60 : 10,
            child: NativeAd(
              height: 60,
              builder: (context, child) {
                return Material(
                  elevation: 8,
                  child: child,
                );
              },
              buildLayout: adDefaultLayoutBuilder,
              loading: Text(''),
              error: Text(''),
              icon: AdImageView(padding: EdgeInsets.only(left: 6)),
              headline: AdTextView(
                  style: TextStyle(
                color: Colors.white.withOpacity(0.8),
              )),
              advertiser: AdTextView(
                  style: TextStyle(
                color: Colors.white.withOpacity(0.7),
              )),
              body: AdTextView(
                  style: TextStyle(
                color: Colors.white.withOpacity(0.8),
              )),
              media: AdMediaView(height: 70, width: 120),
              attribution: AdTextView(
                width: WRAP_CONTENT,
                height: WRAP_CONTENT,
                padding: EdgeInsets.symmetric(horizontal: 2, vertical: 0),
                margin: EdgeInsets.only(right: 4),
                maxLines: 1,
                text: 'Ad',
                decoration: AdDecoration(
                  borderRadius: AdBorderRadius.all(10),
                  border: BorderSide(color: Colors.black, width: 1),
                  backgroundColor: primaryColor,
                ),
                style: TextStyle(
                    color: Colors.white.withOpacity(0.8),
                    fontWeight: FontWeight.bold),
              ),
              button: AdButtonView(
                width: WRAP_CONTENT,
                height: WRAP_CONTENT,
                padding: EdgeInsets.symmetric(horizontal: 6, vertical: 0),
                margin: EdgeInsets.only(left: 0, right: 6),
                //text: 'Learn More',
                decoration: AdDecoration(
                  borderRadius: AdBorderRadius.all(30),
                  border: BorderSide(
                      color: Colors.white.withOpacity(0.9), width: 1),
                  backgroundColor: Color(0xFF111111),
                ),
                textStyle: TextStyle(
                  color: Colors.white.withOpacity(0.9),
                  fontSize: 14,
                  fontFamily: 'HelveticaNeueeText',
                ),
              ),
            ),
          ),

Thank you!

Does the package support mediation?

If yes, can you please give me the steps on adapters' implementation and everything I need to get mediation ready and running. If no, I will still use the package bcz it is the best on pub as of now. Thank you.

BannerAd not working with Virtual Display

BannerAd is only working with hybrid composition. Version 0.9.4

Full fix

This problem is probably caused because the way BannerAd is treated. This probably will be fixed after the BannerAd rewrite (after iOS implementation).

Fix for now

For now, useHybridComposition will default to true in BannerAd.

Flutter Doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 1.22.6, on Microsoft Windows [versão 10.0.19041.804], locale pt-BR)

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[!] Android Studio (version 4.1.0)
  X Flutter plugin not installed; this adds Flutter specific functionality.   
  X Dart plugin not installed; this adds Dart specific functionality.
[√] VS Code (version 1.53.2)        
[√] Connected device (1 available)  

! Doctor found issues in 1 category.

Real ads not showing but test ads are

Real ads shows on emulator but doesnt shows on the real device. Why so ?
Actually, real devices show test ads, but real ad doesnt seems to be showing.

NativeAd becomes unresponsive and its texts disappear after removing & re-adding it to the widget tree

In your example app, I just added a button to toggle show/hide the first NativeAd (which is attached to a controller). After it's shown again, it is unresponsive and its texts won't show up as can bee seen in the screenshots. This is the code I edited:

class _NativeAdsState extends State<NativeAds>
    with AutomaticKeepAliveClientMixin {
  Widget child;

  final controller = NativeAdController();
  bool _showTheTopNativeAd = true;

  @override
  void initState() {
    super.initState();
    controller.load();
    controller.onEvent.listen((event) {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (child != null) return child;
    return RefreshIndicator(
      onRefresh: () async {
        setState(() => child = SizedBox());
        await Future.delayed(Duration(milliseconds: 20));
        setState(() => child = null);
      },
      child: ListView(
        padding: EdgeInsets.all(10),
        children: [
          if (controller.isLoaded && _showTheTopNativeAd)
            NativeAd(
              controller: controller,
              height: 60,
              builder: (context, child) {
                return Material(
                  elevation: 8,
                  child: child,
                );
              },
              buildLayout: adBannerLayoutBuilder,
              loading: Text('loading'),
              error: Text('error'),
              icon: AdImageView(padding: EdgeInsets.only(left: 6)),
              headline: AdTextView(style: TextStyle(color: Colors.black)),
              advertiser: AdTextView(style: TextStyle(color: Colors.black)),
              body: AdTextView(style: TextStyle(color: Colors.black)),
              media: AdMediaView(height: 70, width: 120),
              button: AdButtonView(
                margin: EdgeInsets.only(left: 6, right: 6),
                textStyle: TextStyle(color: Colors.green, fontSize: 14),
                elevation: 18,
                elevationColor: Colors.amber,
              ),
            ),
          SizedBox(height: 10),
          FlatButton(
              onPressed: () {
                setState(() {
                  _showTheTopNativeAd = ! _showTheTopNativeAd;
                });
              },

              child: Text("Toggle Show")),
        ],
      ),
    );
  }

Screen Shots:

Before hiding it After hiding it
Screenshot_20210421-231600 Screenshot_20210421-231611

App freeze when app has no interent connection

When there are no internet connection app freezes while loading ads on the app
I put the below code on the bottom navigation bar so when there is no internet connection app freezes.
while loading native ads

NativeAd(
            controller: _nativAdController,
            height: 60,
            buildLayout: adBannerLayoutBuilder,
            loading: Text('Loading'),
            error: Text('Error'),
            icon: AdImageView(padding: EdgeInsets.only(left: 6)),
            headline: AdTextView(
              style: TextStyle(color: Colors.black),
              maxLines: 1,
            ),
            advertiser: AdTextView(style: TextStyle(color: Colors.black)),
            body: AdTextView(style: TextStyle(color: Colors.black)),
            media: AdMediaView(height: 70, width: 120),
            button: AdButtonView(
              margin: EdgeInsets.only(left: 6, right: 6),
              textStyle: TextStyle(color: Colors.green, fontSize: 14),
            ),
          ),

Sometimes on internet connection too
Screenshot_2021-02-14-14-01-52-277_com.miui.bugreport.jpg
Screenshot_2021-02-14-14-01-54-387_com.miui.bugreport.jpg
Screenshot_2021-02-14-14-02-18-256_com.miui.bugreport.jpg

Warning from google: Not all asset views lie inside the native ad view.

I/Ads ( 4249): Received log message: Google:HTML Not all asset views lie inside the native ad view. This indicates an integration problem. Such implementations will not be supported in the future. Please make sure that all native ad assets are rendered inside the native ad view.

Getting this log message with the example code.

preload or reuse ad on list

Hello,

I have a ListView where I insert a NativeAd for every N number of items.

The issue is that the whole list lags when it first shows new ads for each NativeAd being loaded in the list, probably because it is loading it and/or rendering it for the first time. After that, the list scroll speed is butter smooth again (until a new NativeAd is added to the list of course).

Do you have some idea on how to prevent it?

I was thinking of preloading the ad so it will simply render inside the list or a way to reuse already loaded ads again (maybe separate the ad state to the controller or a state class and then pass it to multiple NativeAd objects so each one of these would simply render the same already loaded ad again).

Edit: Just for completeness, I saw that other libraries normally allow the user to set the number max adds to use in the app at the same time, so if the user sets 3, it will load only 3 ads and then "recycle" these if you add more ads to the page. Maybe something like that would resolve the issue?

load open app ad failure

My intention is to continue to display the Splash page after the ad has been displayed for a period of time. If there is any problem during the loading or display of the ad, the Splash page will be displayed directly.

final AppOpenAd appOpenAd = AppOpenAd();

class SplashPage extends StatefulWidget {
  final FlutterLocalNotificationsPlugin flutterLocalNotifications;
  final AndroidNotificationChannel channel;

  const SplashPage({
    Key? key,
    required this.flutterLocalNotifications,
    required this.channel,
  }) : super(key: key);

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

class _SplashPageState extends State<SplashPage> {
  @override
  void initState() {
    super.initState();
    appOpenAd.onEvent.listen((e) {
      final event = e.keys.first;
      // final info = e.values.first;
      switch (event) {
        case FullScreenAdEvent.loading:
          print('loading');
          break;
        case FullScreenAdEvent.loadFailed:
          print('load failed');
          break;
        case FullScreenAdEvent.loaded:
          print('loaded');
          break;
        case FullScreenAdEvent.showed:
          print('ad showed');
          NavigatorUtil.push(context, widget);
          break;
        case FullScreenAdEvent.showFailed:
          print('show failed');
          break;
        case FullScreenAdEvent.closed:
          print('ad closed');
          break;
        default:
          break;
      }
    });

    FirebaseMessaging.instance.getInitialMessage().then((message) => {
          if (message != null)
            {
              /// todo
            }
        });

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      var notification = message.notification;
      var android = message.notification?.android;
      if (notification != null && android != null) {
        widget.flutterLocalNotifications.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              widget.channel.id,
              widget.channel.name,
              widget.channel.description,
              icon: 'ic_launcher',
            ),
          ),
        );
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
      NavigatorUtil.push(context, MessageView(),
          settings: RouteSettings(arguments: MessageArguments(message, true)));
    });
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DarkModeBloc, DarkModeState>(
      builder: (context, state) => BlocBuilder<ThemeBloc, ThemeState>(
        builder: (context, themeState) => FutureBuilder(
            future: appOpenAd.load(force: true),
            builder: (BuildContext context, AsyncSnapshot<bool> loadRes) {
              var loadResult = loadRes.data ?? false;
              if (loadResult) {
                if (appOpenAd.isAvailable) {
                  return FutureBuilder(
                    future: appOpenAd.show(),
                    builder:
                        (BuildContext context, AsyncSnapshot<bool> showRes) {
                      Future.delayed(Duration(milliseconds: 500), () {
                        appOpenAd.load(force: true);
                      });
                      return Container();
                    },
                  );
                } else {
                  return _default(themeState);
                }
              } else {
                return _default(themeState);
              }
            }),
      ),
    );
  }

  Widget _default(ThemeState themeState) {
    var _theme = Theme.of(context);
    return SplashScreen(
      seconds: 6,
      title: Text(
        GitterLocalizations.of(context)!.welcome,
        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
      ),
      navigateAfterFuture: _widget(),
      image: Image.network('https://cdn.gitterapp.com/logo/gitter.png'),
      styleTextUnderTheLoader: TextStyle(),
      backgroundColor: _theme.colorScheme.background,
      photoSize: 100.0,
      onClick: () => print(GitterConstants.APP_NAME),
      useLoader: true,
      loadingText: Text(GitterLocalizations.of(context)!.loading),
      loadingTextPadding: EdgeInsets.zero,
      loaderColor: Color(themeState.color!),
    );
  }

  Future<Widget> _widget() async {
    return StringUtil.isNotBlank(GitterManager().token)
        ? TabNavigator()
        : LoginPage();
  }
}

1.0.0-pre BannerAds not showing on iOS with real adUnitIDs

While BannerAds are shown when using test unit ids, they are not shown when using real ad units.

iOS Admob status: ["GADMobileAds": <GADAdapterStatus: 0x280717ed0; state = Ready>]
<Google> Invalid Request. Too many recently failed requests for ad unit ID: ca-app-pub-XXX/YYY. You must wait a few seconds before making another ad request.

Support for non-personalized ads

Hey,

In some cases (like when a European user doesn't give its consent for some tracking cookies), it may be required to show only non-personalized ads. Would it be possible to add support for this in your plugin ?

I haven't checked your source code yet, some I cannot submit a pull request, but here are some links :

If you're okay and if you don't have the time to work on this, I may be able to send a pull request.

Thanks !

Reload/Refresh native ad when first ad is being shown. Is there any way to do it?

I am currently showing a native ad on the home screen of the app. When the user goto the second screen and comes back to the home screen I want to refresh the previous ad. Is there any way by which I can achieve this using this framework?

One more question. Do I have to implement firebase_admob if I'm using this package? As firebase AdMob is being deprecated in April. Does this package support google_mobile_ads?

[Event] Not found click event

Is this event removed? I can not find it to use.

Screen Shot 2021-03-12 at 20 34 29

And seems this event is not supported by other kinds of ad also.
Thanks for this great plugin.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.