Всякий раз, когда я добавляю определенную библиотеку и изменяю androidmanifest.xml в разделе метаданных, приложение flutter продолжает сбой
Я пытаюсь добавить рекламу admob в свое приложение. Все остальное работает нормально, но когда я добавляю этот пакет flutter firebase_admob: ^0.9.0+10, приложение вылетает при запуске.
Документация к этому пакету настаивает на том, чтобы я изменил файл AndroidManifest.xml в разделе метаданных, указав следующую информацию, но когда я это сделаю, приложение все равно вылетит:
<!-- Below is the default meta-data and default commenting statement explaining the meta-data section -->
<!-- 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" />
Я заменил вышеуказанные метаданные на метаданные ниже, как это объясняется в документации пакета firebase-admob.
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544/6300978111"/>
<!-- I'm using sample ad unit id for banner provided here "https://developers.google.com/admob/android/test-ads" -->
Ниже я получаю ошибку:
e: C:\Users\current user\Documents\mobile development\simple_app\android\app\src\main\kotlin\com\example\simple_app\MainActivity.kt: (10, 48): Type mismatch: inferred type is FlutterEngine but PluginRegistry! was expected
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 16s
Finished with error: Gradle task assembleDebug failed with exit code 1
Я не знаю, почему я получаю эту ошибку. Я пробовал разные подходы и похожие пакеты admob, но похожие ошибки продолжают возникать.
2 ответа
Идентификатор вашего приложения неверен. Android:value="ca-app-pub-3940256099942544/6300978111" <--- это идентификатор рекламного блока.
Мне удалось решить проблему с помощью firebase_admob 0.5.3.
В файл pubspec.yaml добавьте следующее:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
firebase_admob: 0.5.3 // add this dependency
В файле AndroidManifest.xml в разделе метаданных это должно быть примерно так:
<!-- 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" />
// Notice that I did not change anything on the meta-data tag this time.
Это файл main.dart. Он показывает, как правильно разместить рекламу admob в своем приложении.
import 'package:flutter/material.dart';
import 'package:my_app/home.dart';
import 'package:firebase_admob/firebase_admob.dart';
const appId = 'ca-app-pub-XXXXXXXXXX~XXXXXXXXXX';
const bannerId = 'ca-app-pub-XXXXXXXXXX/XXXXXXXXX';
const insterstitialId = 'ca-app-pub-XXXXXXXXX/XXXXXXXX';
MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
keywords: <String>['flutterio', 'beautiful apps'],
contentUrl: 'https://flutter.io',
birthday: DateTime.now(),
childDirected: false,
designedForFamilies: false,
gender: MobileAdGender.unknown, // or MobileAdGender.female, MobileAdGender.unknown
testDevices: <String>[], // Android emulators are considered test devices
);
BannerAd myBanner = BannerAd(
// Replace the testAdUnitId with an ad unit id from the AdMob dash.
// https://developers.google.com/admob/android/test-ads
// https://developers.google.com/admob/ios/test-ads
adUnitId: BannerAd.testAdUnitId,
size: AdSize.smartBanner,
targetingInfo: targetingInfo,
listener: (MobileAdEvent event) {
print("BannerAd event is $event");
},
);
void main() {
runApp(FlashlightApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
FirebaseAdMob.instance.initialize(appId: appId);
super.initState();
}
@override
Widget build(BuildContext context) {
myBanner
// typically this happens well before the ad is shown
..load()
..show(
// Positions the banner ad 60 pixels from the bottom of the screen
anchorOffset: 20.0,
// Banner Position
anchorType: AnchorType.bottom,
);
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}