Posts tagged with flutter

I am facing this error on flutter native ads (android):

PlatformException(NativeAdError, Can't find NativeAdFactory with id: homeScreen, null, null)

google_mobile_ads: ^0.13.0 

this is my HomeScreenNativeAd.kt file

class HomeScreenNativeAd(val context: Context) : GoogleMobileAdsPlugin.NativeAdFactory{     override fun createNativeAd(             nativeAd: NativeAd,             customOptions: MutableMap<String, Any>?     ): NativeAdView {         val homeScreenNativeView = LayoutInflater.from(context)                 .inflate(R.layout.home_screen_native_ad, null) as NativeAdView         with(homeScreenNativeView) {             val attributionViewSmall =                     findViewById<TextView>(R.id.tv_home_item_native_ad_attribution_small)             val icon = findViewById<ImageView>(R.id.home_item_bg_image)             val image = nativeAd.icon             if (image != null) {                 attributionViewSmall.visibility = View.VISIBLE                 icon.setImageDrawable(image.drawable)             } else {                 attributionViewSmall.visibility = View.INVISIBLE             }             this.iconView = iconView             val adV =   findViewById<TextView>(R.id.adviser)             adV.text = nativeAd.advertiser             this.advertiserView =adV             val ctaButton =   findViewById<TextView>(R.id.home_screen_cta_button)             ctaButton.text = nativeAd.callToAction             this.callToActionView = ctaButton             val adDesc =   findViewById<TextView>(R.id.home_item_ad_desc)             adDesc.text = nativeAd.body             this.bodyView = ctaButton             val headlineView = findViewById<TextView>(R.id.home_item_ad_title)             headlineView.text = nativeAd.headline             this.headlineView = headlineView             setNativeAd(nativeAd)         }         return homeScreenNativeView     } } 

home_screen_native_ad.xml file

`

<com.google.android.gms.ads.nativead.NativeAdView     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent">     <FrameLayout         android:layout_width="match_parent"         android:layout_height="match_parent">         <RelativeLayout             android:orientation="vertical"             android:layout_width="wrap_content"             android:layout_height="160dp">             <FrameLayout                 android:layout_width="match_parent"                 android:background="#00ffffff"                 android:layout_height="140dp"/>             <RelativeLayout                 android:layout_width="match_parent"                 android:layout_height="190dp"                 android:layout_marginTop="16dp"                 android:layout_marginEnd="16dp"                 android:layout_marginBottom="16dp"                 android:gravity="start"                 android:orientation="horizontal">                 <ImageView                     android:id="@+id/home_item_bg_image"                     android:layout_width="60dp"                     android:layout_height="60dp"                     android:scaleType="centerCrop"                     android:layout_marginLeft="16dp"                     />                 <TextView                     android:id="@+id/home_item_ad_title"                     android:layout_width="220dp"                     android:layout_height="wrap_content"                     android:layout_marginLeft="10dp"                     android:layout_toRightOf="@+id/home_item_bg_image"                     android:ellipsize="end"                     android:lines="1"                     android:maxLines="1"                     android:textColor="#FFFFFFFF"                     android:textSize="20sp"                     tools:text="Headline" />                 <TextView                     android:id="@+id/adviser"                     android:layout_width="229dp"                     android:layout_height="wrap_content"                     android:layout_marginLeft="10dp"                     android:layout_marginTop="32dp"                     android:layout_toRightOf="@+id/home_item_bg_image"                     android:ellipsize="end"                     android:lines="1"                     android:maxLines="1"                     android:textColor="#FFFFFFFF"                     android:textSize="14sp"                     tools:text="Advertiser" />                 <TextView                     android:id="@+id/tv_home_item_native_ad_attribution_small"                     android:layout_width="35dp"                     android:layout_height="20dp"                     android:layout_marginLeft="10dp"                     android:layout_toRightOf="@+id/home_item_ad_title"                     android:background="@color/softOrange"                     android:gravity="center"                     android:lines="1"                     android:maxLines="1"                     android:text="Ad"                     android:textColor="#FFFF"                     android:textSize="12sp" />             </RelativeLayout>             <TextView                 android:id="@+id/home_item_ad_desc"                 android:layout_width="270dp"                 android:layout_height="40dp"                 android:layout_marginTop="85dp"                 android:ellipsize="end"                 android:lines="2"                 android:gravity="center_vertical"                 android:maxLines="2"                 android:textColor="#FFFFFFFF"                 android:textSize="14sp"                 android:layout_marginLeft="16dp"                 tools:text="Headline" />             <TextView                 android:id="@+id/home_screen_cta_button"                 android:layout_width="wrap_content"                 android:layout_marginLeft="10dp"                 android:layout_height="30dp"                 android:layout_toRightOf="@+id/home_item_ad_desc"                 android:layout_marginTop="100dp"                 android:text="INSTALL"                 android:gravity="center"                 android:ellipsize="end"                 android:lines="1"                 android:textColor="#FFF"                 android:maxLines="1"                 android:textSize="18sp"                 />         </RelativeLayout>     </FrameLayout> </com.google.android.gms.ads.nativead.NativeAdView>` 

MainActivity.kt

`class MainActivity : FlutterActivity(){     private val CHANNEL = "verified.cv/channel" //The channel name you set in your main.dart file     override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {         super.configureFlutterEngine(flutterEngine)         MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {             // Note: this method is invoked on the main thread.             call, result ->             if (call.method == "createNotificationChannel") {                 val argData = call.arguments as java.util.HashMap<String, String>                 val completed = createNotificationChannel(argData)                 if (completed == true) {                     result.success(completed)                 } else {                     result.error("Error Code", "Error Message", null)                 }             } else {                 result.notImplemented()             }         }         GoogleMobileAdsPlugin.registerNativeAdFactory(                 flutterEngine, "listTile", ListTileNativeAdFactory(context))         GoogleMobileAdsPlugin.registerNativeAdFactory(                 flutterEngine, "skillCard", SkillCardNativeFactory(context))         GoogleMobileAdsPlugin.registerNativeAdFactory(                 flutterEngine, "homeScreen", HomeScreenNativeAd(context))         GoogleMobileAdsPlugin.registerNativeAdFactory(                 flutterEngine, "feedItem", FeedItemNativeFactory(context))     }     override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {         super.cleanUpFlutterEngine(flutterEngine)         // TODO: Unregister the ListTileNativeAdFactory         GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "listTile")         GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "skillCard")         GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "homeScreen")         GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "feedItem")     }     private fun createNotificationChannel(mapData: HashMap<String, String>): Boolean {         val completed: Boolean         if (VERSION.SDK_INT >= VERSION_CODES.O) {             // Create the NotificationChannel             val id = mapData["id"]             val name = mapData["name"]             val descriptionText = mapData["description"]             // val sound = "your_sweet_sound"             val importance = NotificationManager.IMPORTANCE_HIGH             val mChannel = NotificationChannel(id, name, importance)             mChannel.description = descriptionText             // val soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/raw/your_sweet_sound");             // val att = AudioAttributes.Builder()             //         .setUsage(AudioAttributes.USAGE_NOTIFICATION)             //         .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)             //         .build();             //mChannel.setSound(soundUri, att)             // Register the channel with the system; you can't change the importance             // or other notification behaviors after this             val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager             notificationManager.createNotificationChannel(mChannel)             completed = true         } else {             completed = false         }         return completed     } } ` 
 I/flutter ( 1409): ----------------FIREBASE CRASHLYTICS---------------- I/flutter ( 1409): PlatformException(NativeAdError, Can't find NativeAdFactory with id: homeScreen, null, null) I/flutter ( 1409): #0      StandardMethodCodec.decodeEnvelope package:flutter/…/services/message_codecs.dart:607 I/flutter ( 1409): #1      MethodChannel._invokeMethod package:flutter/…/services/platform_channel.dart:177 I/flutter ( 1409): <asynchronous suspension> I/flutter ( 1409): #2      NativeAd.load package:google_mobile_ads/src/ad_containers.dart:1033 I/flutter ( 1409): <asynchronous suspension> I/flutter ( 1409): ---------------------------------------------------- D/ACodec  ( 1409): dataspace changed to 0x10c40000 (R:2(Limited), P:4(BT601_6_525), M:3(BT601_6), T:3(SMPTE170M)) (

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