Posts tagged with dart

I am trying to add google native ads in my flutter app using this library

https://pub.dev/packages/google_mobile_ads

i am getting this error:

\[log\] NativeAd failed to load: LoadAdError(code: 0, domain: com.google.android.gms.ads, message: Internal error., responseInfo: ResponseInfo(responseId: _-SvZbabD5e-3LUP4oaxkAs, mediationAdapterClassName: , adapterResponses: \[AdapterResponseInfo(adapterClassName: com.google.ads.mediation.admob.AdMobAdapter, latencyMillis: 83, description: { "Adapter": "com.google.ads.mediation.admob.AdMobAdapter", "Latency": 83, "Ad Source Name": "Reservation campaign", "Ad Source ID": "7068401028668408324", "Ad Source Instance Name": "\[DevRel\] \[DO NOT EDIT\] Native Ads Campaign", "Ad Source Instance ID": "3518433842871043", "Credentials": { "pubid": "ca-app-pub-3940256099942544/2247696110/cak=no_cache&cadc=c3&caqid=_-SvZfiWDr-FmsMPtMWtgAM", "campaign_id": "12584073087" }, "Ad Error": { "Code": 0, "Message": "Internal error.", "Domain": "com.google.android.gms.ads", "Cause": "null" } }, adUnitMapping: {pubid: ca-app-pub-3940256099942544/2247696110/cak=no_cache&cadc=c3&caqid=\_-SvZfiWDr-FmsMPtMWtgAM, campaign_id: 12584073087}, adError: AdError(code: 0, domain: com.google.android.gms.ads, message: Internal error.), adSourceName: Reservation campaign, adSourceId: 7068401028668408324, adSourceInstanceName: \[DevRel\] \[DO NOT EDIT\] Native Ads Campaign, adSourceInstanceId: 3518433842871043)\], loadedAdapterResponseInfo: null), responseExtras: {mediation_group_name: Campaign}) 

Minimal Code to Reproduce

Native Controller:

import 'package:get/get.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; class NativeAdController extends GetxController{   NativeAd? ad;   final adLoaded = false.obs; } 

Ad Helper:

import 'dart:developer'; import 'package:flutter/foundation.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import '../controllers/controller_native_ads.dart'; class AdHelper{   static Future<void> initAds() async {     await MobileAds.instance.initialize();   }   void loadInterstitialAd({required VoidCallback onComplete}) {     InterstitialAd.load(       adUnitId: 'ca-app-pub-3940256099942544/1033173712',       request: const AdRequest(),       adLoadCallback: InterstitialAdLoadCallback(         // Called when an ad is successfully received.         onAdLoaded: (ad) {           ad.fullScreenContentCallback = FullScreenContentCallback(             onAdDismissedFullScreenContent: (ad) {               onComplete();             },             onAdFailedToShowFullScreenContent: (ad, error) {               log(error.toString());             },             onAdShowedFullScreenContent: (ad) {               log("Full Screen");             },           );           log('This is the $ad loaded.');         },         // Called when an ad request failed.         onAdFailedToLoad: (LoadAdError error) {           log('InterstitialAd failed to load: $error');         },       ),     );   }   static NativeAd loadNativeAd({required NativeAdController nativeAdController}) {     return NativeAd(       adUnitId: 'ca-app-pub-3940256099942544/2247696110',       listener: NativeAdListener(         onAdLoaded: (ad) {           log('$NativeAd loaded.');           nativeAdController.adLoaded.value = true;         },         onAdFailedToLoad: (ad, error) {           log('$NativeAd failed to load: $error');           ad.dispose();         },       ),       request: const AdRequest(),       // Styling       nativeTemplateStyle: NativeTemplateStyle(         templateType: TemplateType.small,       ),     )..load();   } } 

Test Screen:

import 'package:flutter/material.dart'; import '../controllers/controller_native_ads.dart'; class TestScreen extends StatelessWidget{   TestScreen({super.key});   final adController = Get.put(NativeAdController());   @override   Widget build(BuildContext context) {     adController.ad = AdHelper.loadNativeAd(nativeAdController: adController);     return Scaffold(       bottomNavigationBar: adController.ad != null && adController.adLoaded.isTrue           ? SafeArea(               child: SizedBox(                 height: 80,                 child: AdWidget(ad: adController.ad!),               ),             )           : null,     );   } } 

I am using test id provided by official google docs flutter-quick-start

Can anyone explain me why this error occurs?

The app is crashing on launch after implementing google ads. I'm using an ios simulator. Ads are working fine on the other apps with the same code implementation but not on this app. Others apps are displaying test ads even with original Ad Units IDs. Interstitial Ads and Rewarded Ads are working fine only banner ads got the issue.

The error: To get test ads on this device, set: Objective-C GADMobileAds.sharedInstance.requestConfiguration.testDeviceIdentifiers = @[ kGADSimulatorID ]; Swift GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = [ kGADSimulatorID ]

Code: AdHelper Class

import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'dart:io'; class AdHelper{   //  Android Ad Units   static String _bannerAd_And = 'ca-app-pub-3884661730977437/3917788070';   static String _interAd_And = 'ca-app-pub-3884661730977437/1291624734';   static String _bannerAdTest_And = 'ca-app-pub-3940256099942544/6300978111';   static String _interAdTest_And = 'ca-app-pub-3940256099942544/1033173712';   //  iOS Ad Units   static String _bannerAd_iOS = 'ca-app-pub-3884661730977437/4131225272';   static String _interAd_iOS = 'ca-app-pub-3884661730977437/6845018522';   static String _bannerAdTest_iOS = 'ca-app-pub-3940256099942544/2934735716';   static String _interAdTest_iOS = 'ca-app-pub-3940256099942544/4411468910'; // FN returns Banner AD Unit Id   static String get bannerAdUnitId {     if (Platform.isAndroid) {       return _bannerAdTest_And;     } else if (Platform.isIOS) {       return _bannerAdTest_iOS;     } else {       throw UnsupportedError('Unsupported platform');     }   }   // FN returns Interstitial Ad Unit Id   static String get interAdUnitId {     if (Platform.isAndroid) {       return _interAdTest_And;     } else if (Platform.isIOS) {       return _interAdTest_iOS;     } else {       throw UnsupportedError('Unsupported platform');     }   } } 

AdController

import 'package:get/get.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'AdMob_Helper.dart'; class AdMobController extends GetxController{   ///------------------  Init   @override   void onInit() {     getBannerAd();     super.onInit();   }   ///------------------  Dispose   @override   void onClose() {     bannerAd.dispose();     super.onClose();   }   late BannerAd bannerAd;   bool isBannerLoaded = false;   //   void getBannerAd() {     bannerAd = BannerAd(       adUnitId: AdHelper.bannerAdUnitId,       size: AdSize.banner,       request: AdRequest(),       listener: BannerAdListener(         onAdLoaded: (_) {           isBannerLoaded = true;           update();         },         onAdFailedToLoad: (ad, error) {           // Releases an ad resource when it fails to load           ad.dispose();           print('Ad load failed (code=${error.code} message=${error.message})');         },       ),     );     // TODO: Load an ad     bannerAd.load();     update();   } } 

I would like to know, why these errors and how to solve them, when I use flutter run, flutter returns these errors:

Launching lib\main.dart on BISON in debug mode... Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01 Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01 Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01 Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01 Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01 Formato de par�metros incorreto - Note: Some input files use or override a deprecated API. Note: Recompile with -Xlint:deprecation for details. Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\path_provider_android-2.0.9\android\src\main\java\io\flutter\plugins\pathprovider\PathProviderPlugin.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. e: C:/Users/Arthur Alland/.gradle/caches/transforms-2/files-2.1/ae449724a6ca38888aadaf690b25af94/work-runtime-2.7.0-api.jar!/META-INF/work-runtime_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version  is 1.1.15. FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 6m 1s Running Gradle task 'assembleDebug'...                            365,1s Exception: Gradle task assembleDebug failed with exit code 1 

Android Build Gradle

buildscript {     ext.kotlin_version = '1.3.50'     repositories {                                  google()                  jcenter()     }     dependencies {         classpath 'com.android.tools.build:gradle:4.1.0'         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"     } } allprojects {     repositories {         google()         jcenter()      } } rootProject.buildDir = '../build' subprojects {     project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects {     project.evaluationDependsOn(':app') } task clean(type: Delete) {     delete rootProject.buildDir } 

Gradle Wrapper Properties

distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip 

Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.you_plan">     <!-- io.flutter.app.FlutterApplication is an android.app.Application that          calls FlutterMain.startInitialization(this); in its onCreate method.          In most cases you can leave this as-is, but you if you want to provide          additional functionality it is fine to subclass or reimplement          FlutterApplication and put your custom class here. -->     <application         android:name="io.flutter.app.FlutterApplication"         android:label="you_plan"         android:icon="@mipmap/ic_launcher">         <activity                      android:name=".MainActivity"                          android:launchMode="singleTop"             android:theme="@style/LaunchTheme"             android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"             android:hardwareAccelerated="true"             android:windowSoftInputMode="adjustResize">             <!-- Specifies an Android theme to apply to this Activity as soon as                  the Android process has started. This theme is visible to the user                  while the Flutter UI initializes. After that, this theme continues                  to determine the Window background behind the Flutter UI. -->                           <meta-data               android:name="io.flutter.embedding.android.NormalTheme"               android:resource="@style/NormalTheme"               />             <!-- Displays an Android View that continues showing the launch screen                  Drawable until Flutter paints its first frame, then this splash                  screen fades out. A splash screen is useful to avoid any visual                  gap between the end of Android's launch screen and the painting of                  Flutter's first frame. -->             <meta-data               android:name="io.flutter.embedding.android.SplashScreenDrawable"               android:resource="@drawable/launch_background"               />                         <intent-filter>                 <action android:name="android.intent.action.MAIN"/>                 <category android:name="android.intent.category.LAUNCHER"/>             </intent-filter>         </activity>         <!-- Don't delete the meta-data below.              This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->         <meta-data             android:name="flutterEmbedding"             android:value="2" />               <meta-data     android:name="com.google.android.gms.ads.APPLICATION_ID"     android:value="ca-app-pub-3940256099942544~3347511713"/>     </application> </manifest>

I googled it several times and the problem seems to be with these android files, but I don't have much experience with android

I'm integrating Interstitial ads in my flutter project. But When I declare like this

 InterstitialAd? _interstitialAd; 

I am getting this error:

33:17: Error: Null safety features are disabled for this library. Try removing the package language version or setting the language version to 2.12 or higher.   InterstitialAd? _interstitialAd;                 ^ lib/admob_service.dart:64:20: Error: Null safety features are disabled for this library. Try removing the package language version or setting the language version to 2.12 or higher.     _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(                    ^ lib/admob_service.dart:79:20: Error: Null safety features are disabled for this library. Try removing the package language version or setting the language version to 2.12 or higher.     _interstitialAd!.show(); 

I saw some stackoverflow answers and tried to upgrade the sdk version from

environment:   sdk: ">=2.7.0 <3.0.0" 

to

environment:   sdk: ">=2.12.0 <3.0.0" 

Then I got errors in my whole project.The error message is :

Error: Cannot run with sound null safety, because the following dependencies don't support null safety:  - package:local_database  - package:auto_size_text  - package:queue

Is there any way other than declaring this : InterstitialAd? _interstitialAd;