1

我在使用 google_mobile_ads 时遇到问题,当我尝试颤振教程中的方法时,我不知道如何让它在我的主程序中工作

主要的

    
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:behend/admob_service.dart';
import 'package:behend/provider/alarm_manager.dart';
import 'package:behend/provider/alarm_provider.dart';
import 'package:behend/provider/setting_provider.dart';
import 'package:behend/provider/stats_provider.dart';
import 'package:behend/screen/Tooltips/intro.dart';
import 'package:behend/screen/alarm_appear_screen.dart';
import 'package:behend/utils/app_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'generated/l10n.dart';
import 'admob_service.dart';

Future<void> main() async {

  WidgetsFlutterBinding.ensureInitialized();


  ///para los ads =v
  final initFuture = MobileAds.instance.initialize();
  final adState = AdState(initFuture);


  SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));


  await AndroidAlarmManager.initialize();

  SharedPreferences.getInstance().then((value) {

    AppPreferenceUtil(pref: value);

    runApp(MultiProvider(
      providers: [
        Provider.value(
          value: adState,
            builder: (context, child)),
        ChangeNotifierProvider(
          create: (_) => AlarmManager(),
        ),
        ChangeNotifierProvider(
          create: (_) => SettingProvider(),
        ),
        ChangeNotifierProvider(
          create: (_) => AlarmProvider.full(),
        ),
        ChangeNotifierProvider(
          create: (_) => StatsProvider(),
        )
      ],
      child: MyApp(),
    ));
  });


  //runApp(MyApp());
}


Future<void> alarm() async {

  print("launching alarm entry point____----___");

  WidgetsFlutterBinding.ensureInitialized();
  await AndroidAlarmManager.initialize();

  SharedPreferences.getInstance().then((value) {
    AppPreferenceUtil(pref: value);
    runApp(MultiProvider(providers: [
      ChangeNotifierProvider(
        create: (_) => AlarmManager(),
      ),
      ChangeNotifierProvider(
        create: (_) => AlarmProvider.minimal(),
      )
    ], child: MyApp2()));
  });

  //runApp(MyApp());
}





class MyApp2 extends StatefulWidget {
  @override
  _MyApp2State createState() => _MyApp2State();
}

class _MyApp2State extends State<MyApp2> {
  @override
  void initState() {
    FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
    Provider.of<AlarmManager>(context, listen: false).init(context);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      ),
      child: MaterialApp(
        title: 'Behend',
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          S.delegate,
        ],
        supportedLocales:
        ///[
        /// const Locale('en', ''),
        ///const Locale('es', ''),
        ///],
        S.delegate.supportedLocales,
        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.teal,
          // This makes the visual density adapt to the platform that you run
          // the app on. For desktop platforms, the controls will be smaller and
          // closer together (more dense) than on mobile platforms.
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Consumer<AlarmManager>(
          builder: (context, provider, child) {
            return AlarmAppearScreen(provider.currentAlarmId);
          },
        ),
      ),
    );
  }
}






class MyApp extends StatelessWidget {

  /*static final FirebaseAnalytics analytics = FirebaseAnalytics();
  static final FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);
  // This widget is the root of your application.*/

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    // uncomment this and open this function
    //updateScoreCard();
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      ),
      child: MaterialApp(
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          S.delegate,
        ],
        supportedLocales:
        ///[
        ///const Locale('en', ''),
        ///const Locale('es', ''),
        ///],
        S.delegate.supportedLocales,
        title: 'Behend',
        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,
          // This makes the visual density adapt to the platform that you run
          // the app on. For desktop platforms, the controls will be smaller and
          // closer together (more dense) than on mobile platforms.
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        //home: EasySortScreen(),
//        home: SwitchExample(),
        // home: HomeScreen(), --
        home: Intro(),
        navigatorObservers: <NavigatorObserver>[/*observer*/],
      ),
    );
  }



状态

    
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io';



class AdState {

  Future<InitializationStatus> initialization;

  AdState(this.initialization);




  static String get bannerAdUnitId => Platform.isAndroid


  ///El primer id es para android
      ? 'ca-app-pub-3940256099942544/6300978111'
  ///El segundo id es para IOS
      : 'ca-app-pub-3940256099942544/6300978111';

}

yaml

    name: behend
description: A new Flutter application.

# 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.5.39+29

environment:
  sdk: ">=2.7.0 <3.0.0"





dependencies:
  google_mobile_ads: ^0.11.0+3

  dart_random_choice: ^0.0.2

  curved_navigation_bar:

  flutter:
    sdk: flutter

  flutter_localizations:
    sdk: flutter

  cupertino_icons: ^0.1.3

  provider: ^4.1.2


  percent_indicator: "^2.1.1"

  package_info: ^0.4.0+16

  fl_chart: 0.9.4

  shared_preferences: ^0.5.7+3

  intl: ^0.17.0

  vibration: ^1.4.0

  showcaseview: ^0.1.5

  fluttertoast: ^3.1.0

  android_alarm_manager:
    path: ./android_alarm_manager-0.4.5_11

  #parece que no funciona(deprecated) o pisa el nuevo package de google_mobile_ads
  #(tira error con el package de google ads(si se quita no lo lo tira))

  #firebase_analytics:
  #  path: ./firebase_analytics-5_0_16

  flutter_swiper: 1.1.6

  flutter_tindercard: 0.1.8

  url_launcher: 5.4.10

  flutter_reorderable_list: ^0.1.4

  flutter_statusbarcolor: 0.2.3

  after_layout: ^1.0.7+2

dev_dependencies:
  flutter_test:
    sdk: flutter

# 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/
    - assets/images/
    - assets/images/intro-slider/
    - assets/images/Tooltips/
    - assets/icons/
    - assets/icons/2.0x/
    - assets/icons/3.0x/

  # 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: Circular
      fonts:
        - asset: assets/fonts/CircularStd-Black.ttf
        - asset: assets/fonts/CircularStd-Bold.ttf
    - family: Roboto
      fonts:
        - asset: assets/fonts/Roboto-Bold.ttf
        - asset: assets/fonts/Roboto-Regular.ttf

  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages


flutter_intl:
  enabled: true
  main_locale: en
  class_name: S

由于我无法在我的主要列表中传递该列表中的上下文,因此我尝试了在 Youtube 中找到的其他方法

主要的


    import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:behend/admob_service.dart';
import 'package:behend/provider/alarm_manager.dart';
import 'package:behend/provider/alarm_provider.dart';
import 'package:behend/provider/setting_provider.dart';
import 'package:behend/provider/stats_provider.dart';
import 'package:behend/screen/Tooltips/intro.dart';
import 'package:behend/screen/alarm_appear_screen.dart';
import 'package:behend/utils/app_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'generated/l10n.dart';
import 'admob_service.dart';

Future<void> main() async {

  WidgetsFlutterBinding.ensureInitialized();
  AdMobService.initialize();




/*
  ///para los ads =v
  final initFuture = MobileAds.instance.initialize();
  final adState = AdState(initFuture);
*/



  SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));


  await AndroidAlarmManager.initialize();

  SharedPreferences.getInstance().then((value) {

    AppPreferenceUtil(pref: value);

    runApp(MultiProvider(
      providers: [
        /*Provider.value(
          value: adState,
            builder: (context, child)),*/
        ChangeNotifierProvider(
          create: (_) => AlarmManager(),
        ),
        ChangeNotifierProvider(
          create: (_) => SettingProvider(),
        ),
        ChangeNotifierProvider(
          create: (_) => AlarmProvider.full(),
        ),
        ChangeNotifierProvider(
          create: (_) => StatsProvider(),
        )
      ],
      child: MyApp(),
    ));
  });


  //runApp(MyApp());
}


Future<void> alarm() async {

  print("launching alarm entry point____----___");

  WidgetsFlutterBinding.ensureInitialized();
  await AndroidAlarmManager.initialize();

  SharedPreferences.getInstance().then((value) {
    AppPreferenceUtil(pref: value);
    runApp(MultiProvider(providers: [
      ChangeNotifierProvider(
        create: (_) => AlarmManager(),
      ),
      ChangeNotifierProvider(
        create: (_) => AlarmProvider.minimal(),
      )
    ], child: MyApp2()));
  });

  //runApp(MyApp());
}





class MyApp2 extends StatefulWidget {
  @override
  _MyApp2State createState() => _MyApp2State();
}

class _MyApp2State extends State<MyApp2> {
  @override
  void initState() {
    FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
    Provider.of<AlarmManager>(context, listen: false).init(context);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      ),
      child: MaterialApp(
        title: 'Behend',
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          S.delegate,
        ],
        supportedLocales:
        ///[
        /// const Locale('en', ''),
        ///const Locale('es', ''),
        ///],
        S.delegate.supportedLocales,
        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.teal,
          // This makes the visual density adapt to the platform that you run
          // the app on. For desktop platforms, the controls will be smaller and
          // closer together (more dense) than on mobile platforms.
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Consumer<AlarmManager>(
          builder: (context, provider, child) {
            return AlarmAppearScreen(provider.currentAlarmId);
          },
        ),
      ),
    );
  }
}






class MyApp extends StatelessWidget {

  /*static final FirebaseAnalytics analytics = FirebaseAnalytics();
  static final FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);
  // This widget is the root of your application.*/

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    // uncomment this and open this function
    //updateScoreCard();
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
      ),
      child: MaterialApp(
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          S.delegate,
        ],
        supportedLocales:
        ///[
        ///const Locale('en', ''),
        ///const Locale('es', ''),
        ///],
        S.delegate.supportedLocales,
        title: 'Behend',
        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,
          // This makes the visual density adapt to the platform that you run
          // the app on. For desktop platforms, the controls will be smaller and
          // closer together (more dense) than on mobile platforms.
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        //home: EasySortScreen(),
//        home: SwitchExample(),
        // home: HomeScreen(), --
        home: Intro(),
        navigatorObservers: <NavigatorObserver>[/*observer*/],
      ),
    );
  }

广告状态


import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io';

/*

class AdState {

  Future<InitializationStatus> initialization;

  AdState(this.initialization);




  static String get bannerAdUnitId => Platform.isAndroid


  ///El primer id es para android
      ? 'ca-app-pub-3940256099942544/6300978111'
  ///El segundo id es para IOS
      : 'ca-app-pub-3940256099942544/6300978111';

}

*/


class AdMobService {

  static String get bannerAdUnitId => Platform.isAndroid

      ///El primer id es para android
      ? 'ca-app-pub-3940256099942544/6300978111'
      ///El segundo id es para IOS
      : 'ca-app-pub-3940256099942544/6300978111';

  static initialize () {
    if (MobileAds.instance == null){
      MobileAds.instance.initialize();
    }
  }

  static BannerAd createBannerAd() {
    BannerAd ad = new BannerAd(
      adUnitId: bannerAdUnitId,
      size: AdSize.banner,
      request: AdRequest(),
      listener: AdListener(
        onAdLoaded: (Ad ad) => print("Ad loaded"),
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          ad.dispose();
        },
        onAdOpened: (Ad ad) => print("ad opened"),
        onAdClosed: (Ad ad) => print("ad closed")
      )
    );
  return ad;
  }

}

它在这里运行,但它给了我这个错误(只有当我激活了 google_mobile_ads 包时才会发生)


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\negre\.gradle\caches\transforms-2\files-2.1\6860be4bd435a3ae0d9b52a862c3efa5\play-services-ads-lite-19.7.0\AndroidManifest.xml:27:5-43:15: AAPT: error: unexpected element <queries> found in <manifest>.


* 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 18s
The build failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetifier to solve the incompatibility.
Building plugin android_alarm_manager...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin flutter_statusbarcolor...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin fluttertoast...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin google_mobile_ads...
Running Gradle task 'assembleAarRelease'...


FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\negre\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\google_mobile_ads-0.11.0+3\android\build.gradle' line: 22

* What went wrong:
A problem occurred evaluating root project 'google_mobile_ads'.
> Failed to apply plugin [id 'com.android.internal.version-check']
   > Minimum supported Gradle version is 6.5. Current version is 5.6.4. If using the gradle wrapper, try editing the distributionUrl in C:\Users\negre\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\google_mobile_ads-0.11.0+3\android\gradle\wrapper\gradle-wrapper.properties to gradle-6.5-all.zip

* 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 1s

Exception: The plugin google_mobile_ads could not be built due to the issue above.

4

1 回答 1

3

安卓/build.gradle

打开build.gradle文件。检查 Android Gradle Plugin 4.1或更高版本。如果它小于4.1,则将Gradle 插件更改为如下代码

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        ...
    }

android/gradle/wrapper/gradle-wrapper.properties

打开gradle-wrapper.properties文件。将distributionUrl更改为以下行。

distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip

然后运行flutter clean命令

最后,重新启动 IDE构建应用程序

这就是我解决这个问题的方法。希望这也能解决您的问题。

于 2021-04-15T09:32:07.023 回答