Flutter广告集成插件easy_ads_flutter的使用

发布于 1周前 作者 h691938207 来自 Flutter

Flutter广告集成插件easy_ads_flutter的使用

简介

Easy Ads Flutter 是一个用于轻松将不同广告网络集成到Flutter应用中的插件。它支持Google Mobile Ads、Facebook Audience Network、Unity Ads和AppLovin Max Ads等广告网络,并且还支持Admob Mediation。此外,它还提供了GDPR和隐私选项合规的支持。

Features

  • 支持多种广告类型:Banner、AppOpen、Interstitial(插屏)、Rewarded(激励)广告。
  • 支持Admob Mediation。
  • 提供GDPR和隐私选项合规的支持。

平台特定设置

iOS

  1. 更新Info.plist
    • 添加必要的广告SDK标识符。
    <key>GADApplicationIdentifier</key>
    <string>YOUR_SDK_KEY</string>
    
    • 添加SKAdNetworkItems以确保所有广告网络正常工作。可以参考示例

Android

  1. 更新AndroidManifest.xml
    <manifest>
        <application>
            <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
            <meta-data
                android:name="com.google.android.gms.ads.APPLICATION_ID"
                android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
        </application>
    </manifest>
    

初始化广告ID

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

class TestAdIdManager extends IAdIdManager {
  const TestAdIdManager();

  @override
  AppAdIds? get admobAdIds => AppAdIds(
    appId: Platform.isAndroid
        ? 'ca-app-pub-3940256099942544~3347511713'
        : 'ca-app-pub-3940256099942544~1458002511',
    appOpenId: Platform.isAndroid
        ? 'ca-app-pub-3940256099942544/3419835294'
        : 'ca-app-pub-3940256099942544/5662855259',
    bannerId: 'ca-app-pub-3940256099942544/6300978111',
    interstitialId: 'ca-app-pub-3940256099942544/1033173712',
    rewardedId: 'ca-app-pub-3940256099942544/5224354917',
  );

  @override
  AppAdIds? get unityAdIds => AppAdIds(
    appId: Platform.isAndroid ? '4374881' : '4374880',
    bannerId: Platform.isAndroid ? 'Banner_Android' : 'Banner_iOS',
    interstitialId:
    Platform.isAndroid ? 'Interstitial_Android' : 'Interstitial_iOS',
    rewardedId: Platform.isAndroid ? 'Rewarded_Android' : 'Rewarded_iOS',
  );

  @override
  AppAdIds? get appLovinAdIds => AppAdIds(
    appId:
    'OeKTS4Zl758OIlAs3KQ6-3WE1IkdOo3nQNJtRubTzlyFU76TRWeQZAeaSMCr9GcZdxR4p2cnoZ1Gg7p7eSXCdA',
    bannerId: Platform.isAndroid ? 'b2c4f43d3986bcfb' : '80c269494c0e45c2',
    interstitialId:
    Platform.isAndroid ? 'c48f54c6ce5ff297' : 'e33147110a6d12d2',
    rewardedId:
    Platform.isAndroid ? 'ffbed216d19efb09' : 'f4af3e10dd48ee4f',
  );

  @override
  AppAdIds? get fbAdIds => AppAdIds(
    appId: 'YOUR_APP_ID',
    interstitialId: 'VID_HD_16_9_15S_LINK#YOUR_PLACEMENT_ID',
    bannerId: 'IMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID',
    rewardedId: 'VID_HD_16_9_46S_APP_INSTALL#YOUR_PLACEMENT_ID',
  );
}

初始化SDK

import 'package:easy_ads_flutter/easy_ads_flutter.dart';
import 'package:flutter/material.dart';

const IAdIdManager adIdManager = TestAdIdManager();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await ConsentManager.gatherGdprConsent(
      debugGeography: kDebugMode ? DebugGeography.debugGeographyEea : null);
  await ConsentManager.gatherPrivacyConsent();

  await EasyAds.instance.initialize(
    isShowAppOpenOnAppStateChange: false,
    adIdManager,
    unityTestMode: true,
    adMobAdRequest: const AdRequest(),
    admobConfiguration: RequestConfiguration(testDeviceIds: []),
    fbTestingId: '73f92d66-f8f6-4978-999f-b5e0dd62275a',
    fbTestMode: true,
    showAdBadge: Platform.isIOS,
    fbiOSAdvertiserTrackingEnabled: true,
  );

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Easy Ads Example',
      home: CountryListScreen(),
    );
  }
}

显示广告

插屏广告和激励广告

void _showAd(AdNetwork adNetwork, AdUnitType adUnitType) {
  if (EasyAds.instance.showAd(
    adUnitType,
    adNetwork: adNetwork,
    context: context,
    loaderDuration: 1,
  )) {
    // Canceling the last callback subscribed
    _streamSubscription?.cancel();
    // Listening to the callback from showRewardedAd()
    _streamSubscription = EasyAds.instance.onEvent.listen((event) {
      if (event.adUnitType == adUnitType) {
        _streamSubscription?.cancel();
        goToNextScreen(adNetwork: adNetwork);
      }
    });
  } else {
    goToNextScreen(adNetwork: adNetwork);
  }
}

Banner广告

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Ad Network List"),
    ),
    body: Column(
      children: [
        SomeWidget(),
        const Spacer(),
        EasyBannerAd(
            adNetwork: AdNetwork.admob, adSize: AdSize.mediumRectangle),
      ],
    ),
  );
}

Smart Banner广告

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Ad Network List"),
    ),
    body: Column(
      children: [
        SomeWidget(),
        const Spacer(),
        const EasySmartBannerAd(
          priorityAdNetworks: [
            AdNetwork.facebook,
            AdNetwork.admob,
            AdNetwork.unity,
            AdNetwork.appLovin,
          ],
          adSize: AdSize.largeBanner,
        ),
      ],
    ),
  );
}

监听回调

StreamSubscription? _streamSubscription;

if (EasyAds.instance.showInterstitialAd()) {
  // Canceling the last callback subscribed
  _streamSubscription?.cancel();
  // Listening to the callback from showInterstitialAd()
  _streamSubscription =
  EasyAds.instance.onEvent.listen((event) {
    if (event.adUnitType == AdUnitType.interstitial &&
        event.type == AdEventType.adDismissed) {
      _streamSubscription?.cancel();
      goToNextScreen(countryList[index]);
    }
  });
}

完整示例代码

import 'dart:async';
import 'dart:io';

import 'package:easy_ads_flutter/easy_ads_flutter.dart';
import 'package:flutter/material.dart';

const IAdIdManager adIdManager = TestAdIdManager();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await ConsentManager.gatherGdprConsent(
      debugGeography: kDebugMode ? DebugGeography.debugGeographyEea : null);
  await ConsentManager.gatherPrivacyConsent();

  await EasyAds.instance.initialize(
    isShowAppOpenOnAppStateChange: false,
    adIdManager,
    unityTestMode: true,
    adMobAdRequest: const AdRequest(),
    admobConfiguration: RequestConfiguration(testDeviceIds: []),
    fbTestingId: '73f92d66-f8f6-4978-999f-b5e0dd62275a',
    fbTestMode: true,
    showAdBadge: Platform.isIOS,
    fbiOSAdvertiserTrackingEnabled: true,
  );

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Easy Ads Example',
      home: CountryListScreen(),
    );
  }
}

class CountryListScreen extends StatefulWidget {
  const CountryListScreen({Key? key}) : super(key: key);

  @override
  State<CountryListScreen> createState() => _CountryListScreenState();
}

class _CountryListScreenState extends State<CountryListScreen> {
  StreamSubscription? _streamSubscription;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Ad Network List"),
        centerTitle: true,
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Text(
                'AppOpen',
                style: Theme.of(context)
                    .textTheme
                    .headlineMedium!
                    .copyWith(color: Colors.blue, fontWeight: FontWeight.bold),
              ),
              AdButton(
                networkName: 'Admob AppOpen',
                onTap: () => _showAd(AdNetwork.admob, AdUnitType.appOpen),
              ),
              const Divider(thickness: 2),
              Text(
                'Interstitial',
                style: Theme.of(context)
                    .textTheme
                    .headlineMedium!
                    .copyWith(color: Colors.blue, fontWeight: FontWeight.bold),
              ),
              AdButton(
                networkName: 'Admob Interstitial',
                onTap: () => _showAd(AdNetwork.admob, AdUnitType.interstitial),
              ),
              AdButton(
                networkName: 'Facebook Interstitial',
                onTap: () =>
                    _showAd(AdNetwork.facebook, AdUnitType.interstitial),
              ),
              AdButton(
                networkName: 'Unity Interstitial',
                onTap: () => _showAd(AdNetwork.unity, AdUnitType.interstitial),
              ),
              AdButton(
                networkName: 'Applovin Interstitial',
                onTap: () =>
                    _showAd(AdNetwork.appLovin, AdUnitType.interstitial),
              ),
              AdButton(
                networkName: 'Available Interstitial',
                onTap: () => _showAvailableAd(AdUnitType.interstitial),
              ),
              const Divider(thickness: 2),
              Text(
                'Rewarded',
                style: Theme.of(context)
                    .textTheme
                    .headlineMedium!
                    .copyWith(color: Colors.blue, fontWeight: FontWeight.bold),
              ),
              AdButton(
                networkName: 'Admob Rewarded',
                onTap: () => _showAd(AdNetwork.admob, AdUnitType.rewarded),
              ),
              AdButton(
                networkName: 'Facebook Rewarded',
                onTap: () => _showAd(AdNetwork.facebook, AdUnitType.rewarded),
              ),
              AdButton(
                networkName: 'Unity Rewarded',
                onTap: () => _showAd(AdNetwork.unity, AdUnitType.rewarded),
              ),
              AdButton(
                networkName: 'Applovin Rewarded',
                onTap: () => _showAd(AdNetwork.appLovin, AdUnitType.rewarded),
              ),
              AdButton(
                networkName: 'Available Rewarded',
                onTap: () => _showAvailableAd(AdUnitType.rewarded),
              ),
              const EasySmartBannerAd(
                priorityAdNetworks: [
                  AdNetwork.facebook,
                  AdNetwork.admob,
                  AdNetwork.unity,
                  AdNetwork.appLovin,
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showAd(AdNetwork adNetwork, AdUnitType adUnitType) {
    if (EasyAds.instance.showAd(
      adUnitType,
      adNetwork: adNetwork,
      context: context,
      loaderDuration: 1,
    )) {
      _streamSubscription?.cancel();
      _streamSubscription = EasyAds.instance.onEvent.listen((event) {
        if (event.adUnitType == adUnitType) {
          _streamSubscription?.cancel();
          goToNextScreen(adNetwork: adNetwork);
        }
      });
    } else {
      goToNextScreen(adNetwork: adNetwork);
    }
  }

  void _showAvailableAd(AdUnitType adUnitType) {
    if (EasyAds.instance.showAd(adUnitType)) {
      _streamSubscription?.cancel();
      _streamSubscription = EasyAds.instance.onEvent.listen((event) {
        if (event.adUnitType == adUnitType) {
          _streamSubscription?.cancel();
          goToNextScreen();
        }
      });
    } else {
      goToNextScreen();
    }
  }

  void goToNextScreen({AdNetwork? adNetwork}) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CountryDetailScreen(adNetwork: adNetwork),
      ),
    );
  }
}

class CountryDetailScreen extends StatefulWidget {
  final AdNetwork? adNetwork;
  const CountryDetailScreen({Key? key, this.adNetwork}) : super(key: key);

  @override
  State<CountryDetailScreen> createState() => _CountryDetailScreenState();
}

class _CountryDetailScreenState extends State<CountryDetailScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('United States'),
        centerTitle: true,
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: 200,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: NetworkImage(
                    'https://cdn.britannica.com/33/4833-050-F6E415FE/Flag-United-States-of-America.jpg'),
              ),
            ),
          ),
          (widget.adNetwork == null)
              ? const EasySmartBannerAd()
              : EasyBannerAd(
                  adNetwork: widget.adNetwork!,
                  adSize: AdSize.largeBanner,
                ),
          const Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.all(20.0),
                child: Text(
                  'The U.S. is a country of 50 states covering a vast swath of North America, with Alaska in the northwest and Hawaii extending the nation’s presence into the Pacific Ocean. Major Atlantic Coast cities are New York, a global finance and culture center, and capital Washington, DC. Midwestern metropolis Chicago is known for influential architecture and on the west coast, Los Angeles\' Hollywood is famed for filmmaking',
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 22),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class AdButton extends StatelessWidget {
  final String networkName;
  final VoidCallback onTap;
  const AdButton({Key? key, required this.onTap, required this.networkName})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            networkName,
            style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w300),
          ),
        ),
      ),
    );
  }
}

通过以上步骤和示例代码,你可以快速地将easy_ads_flutter集成到你的Flutter项目中,并展示各种类型的广告。希望这些信息对你有所帮助!


更多关于Flutter广告集成插件easy_ads_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter广告集成插件easy_ads_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用easy_ads_flutter插件的详细步骤和代码示例。easy_ads_flutter是一个方便集成多种广告平台的Flutter插件。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加easy_ads_flutter的依赖:

dependencies:
  flutter:
    sdk: flutter
  easy_ads_flutter: ^x.y.z  # 请替换为最新版本号

2. 导入插件

在你的Dart文件中导入easy_ads_flutter

import 'package:easy_ads_flutter/easy_ads_flutter.dart';

3. 初始化插件

在你的应用启动时(通常在main.dart中),初始化EasyAdsFlutter插件:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  EasyAdsFlutter.instance.init(
    appId: 'YOUR_ADMOB_APP_ID',  // 替换为你的AdMob应用ID
    bannerAdUnitId: 'YOUR_BANNER_AD_UNIT_ID',  // 替换为你的Banner广告单元ID
    interstitialAdUnitId: 'YOUR_INTERSTITIAL_AD_UNIT_ID',  // 替换为你的Interstitial广告单元ID
    rewardedAdUnitId: 'YOUR_REWARDED_AD_UNIT_ID',  // 替换为你的Rewarded广告单元ID
  );
  
  runApp(MyApp());
}

4. 显示Banner广告

在你的UI组件中,使用EasyAdsFluttershowBannerAd方法显示Banner广告:

import 'package:flutter/material.dart';
import 'package:easy_ads_flutter/easy_ads_flutter.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Easy Ads Flutter Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 调用插件的showBannerAd方法显示Banner广告
            EasyAdsFlutter.instance.showBannerAd(
              anchor: AnchorType.TOP,
              horizontalAlignment: HorizontalAlignment.CENTER,
            ),
            Text(
              'Scroll down to see the banner ad',
              style: TextStyle(fontSize: 20),
            ),
          ],
        ),
      ),
    );
  }
}

5. 显示Interstitial广告

你可以使用EasyAdsFlutterloadInterstitialAdshowInterstitialAd方法来加载和显示Interstitial广告:

class _MyHomePageState extends State<MyHomePage> {
  bool _isInterstitialLoaded = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Easy Ads Flutter Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                // 加载Interstitial广告
                bool loaded = await EasyAdsFlutter.instance.loadInterstitialAd();
                setState(() {
                  _isInterstitialLoaded = loaded;
                });

                if (_isInterstitialLoaded) {
                  // 显示Interstitial广告
                  EasyAdsFlutter.instance.showInterstitialAd();
                }
              },
              child: Text('Show Interstitial Ad'),
            ),
          ],
        ),
      ),
    );
  }
}

6. 显示Rewarded广告

类似地,你可以使用EasyAdsFlutterloadRewardedAdshowRewardedAd方法来加载和显示Rewarded广告:

class _MyHomePageState extends State<MyHomePage> {
  bool _isRewardedLoaded = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Easy Ads Flutter Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                // 加载Rewarded广告
                bool loaded = await EasyAdsFlutter.instance.loadRewardedAd();
                setState(() {
                  _isRewardedLoaded = loaded;
                });

                if (_isRewardedLoaded) {
                  // 显示Rewarded广告
                  EasyAdsFlutter.instance.showRewardedAd().then((result) {
                    if (result) {
                      // 用户完成观看广告后的回调
                      print('User completed the rewarded ad.');
                    } else {
                      // 用户未完成观看广告
                      print('User did not complete the rewarded ad.');
                    }
                  });
                }
              },
              child: Text('Show Rewarded Ad'),
            ),
          ],
        ),
      ),
    );
  }
}

以上就是在Flutter项目中集成和使用easy_ads_flutter插件的完整步骤和代码示例。请确保替换相应的广告单元ID,并根据需要进行进一步的自定义。

回到顶部