Ich integriere Admob in meine Flutter -App mit dem Plugin von Google_Mobile_Ads. Belohnte Anzeigen funktionieren gut, aber meine native Anzeige lädt nicht. Ich habe überprüft, ob die AD -IDs korrekt sind und dass die Werks -ID "AdfactoryExample" zwischen meinem Fluttercode und dem nativen Android -Code übereinstimmt. Unten finden Sie die relevanten Codesegmente: < /p>
Flutter -AD -Komponente (Dart): < /p>
class _HomeScreenState extends State {
RewardedAd? _rewardedAd;
bool _isRewardedAdReady = false;
// Native ad fields.
NativeAd? _nativeAd;
bool _isNativeAdLoaded = false;
@override
void initState() {
super.initState();
_loadRewardedAd();
_loadNativeAd(); // Load the native ad on initialization.
}
void _loadRewardedAd() {
RewardedAd.load(
adUnitId: 'ca-app-pub-rewardId', // Replace with your rewarded ad unit ID.
request: const AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
_rewardedAd = ad;
setState(() {
_isRewardedAdReady = true;
});
},
onAdFailedToLoad: (LoadAdError error) {
print('RewardedAd failed to load: $error');
setState(() {
_isRewardedAdReady = false;
});
},
),
);
}
// New method to load the native ad.
void _loadNativeAd() {
_nativeAd = NativeAd(
adUnitId: 'ca-app-pub-nativeId', // Replace with your native ad unit ID.
factoryId: 'adFactoryExample', // Must match the native side.
request: const AdRequest(),
listener: NativeAdListener(
onAdLoaded: (ad) {
setState(() {
_isNativeAdLoaded = true;
});
print('Native ad loaded.');
},
onAdFailedToLoad: (ad, error) {
ad.dispose();
print('Native ad failed to load: $error');
setState(() {
_isNativeAdLoaded = false;
});
},
),
);
_nativeAd!.load();
}
void _showRewardedAd() {
if (_isRewardedAdReady && _rewardedAd != null) {
_rewardedAd!.show(
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
print('User earned: ${reward.amount} ${reward.type}');
},
);
_rewardedAd = null;
setState(() {
_isRewardedAdReady = false;
});
_loadRewardedAd();
}
}
Widget _nativeAdWidget() {
if (_isNativeAdLoaded && _nativeAd != null) {
return Container(
height: 100,
child: AdWidget(ad: _nativeAd!),
);
} else {
return Container(
height: 100,
color: Colors.grey[300],
child: const Center(child: Text('Native ad loading...')),
);
}
}
@override
void dispose() {
_rewardedAd?.dispose();
_nativeAd?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AdMob Screen'),
actions: [
IconButton(
icon: const Icon(Icons.payment),
onPressed: () {
Navigator.pushNamed(context, '/payment');
},
)
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: const Text('Show Reward Ad'),
onPressed: _isRewardedAdReady ? _showRewardedAd : null,
),
const SizedBox(height: 20),
_nativeAdWidget(),
const SizedBox(height: 20),
ElevatedButton(
child: const Text('Go to Payment Screen'),
onPressed: () {
Navigator.pushNamed(context, '/payment');
},
),
],
),
),
);
}
}
< /code>
Android Build.gradle (App-Level): < /p>
import java.util.Properties
val keystoreProperties = Properties()
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(keystorePropertiesFile.inputStream())
}
plugins {
id("com.android.application")
id("kotlin-android")
id("dev.flutter.flutter-gradle-plugin")
}
android {
namespace = "pname"
compileSdk = flutter.compileSdkVersion
ndkVersion = "27.0.12077973"
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_11.toString()
}
defaultConfig {
applicationId = "pname"
minSdk = 23
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
}
}
dependencies {
implementation("com.google.android.gms:play-services-ads:24.1.0")
// ... other dependencies
}
flutter {
source = "../.."
}
apply(plugin = "com.google.gms.google-services")
< /code>
MainActivity.kt:
package pname
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import com.google.android.gms.ads.MobileAds
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this) { initializationStatus ->
// Optional: handle initialization status.
}
// Register the native ad factory.
flutterEngine.platformViewsController
.registry
.registerViewFactory("adFactoryExample", NativeAdFactory(this))
}
}
< /code>
NATIVEADFACTORY.KT
package pname
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
import io.flutter.plugin.common.StandardMessageCodec
// Factory to create native ad views.
class NativeAdFactory(private val context: Context) : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
override fun create(context: Context?, id: Int, args: Any?): PlatformView {
return NativeAdView(context)
}
}
// A simple PlatformView that inflates a native ad layout.
class NativeAdView(private val context: Context?) : PlatformView {
// Ensure you have a layout resource named "native_ad_layout.xml" in res/layout.
private val adView: View = LayoutInflater.from(context).inflate(R.layout.native_ad_layout, null)
override fun getView(): View = adView
override fun dispose() {}
}
< /code>
Ich habe doppelt überprüft, dass die Werks-ID "AdfactoryExample" zwischen meinem Flattern und meinem nativen Code konsistent ist. Belohnte Anzeigen laden und werden korrekt angezeigt, aber die native Anzeige erscheint nie. Hat jemand irgendwelche Vorschläge darüber, was möglicherweise dazu führt, dass die native Anzeige nicht laden oder angezeigt wird?>
Native Anzeige nicht in Flutter -App geladen trotz der korrekten Fabrik -ID -Registrierung ⇐ Android
-
- Similar Topics
- Replies
- Views
- Last post