Flutter移动广告集成插件flutter_yandex_mobile_ads的使用

Flutter移动广告集成插件flutter_yandex_mobile_ads的使用

本插件支持

Android:
  • ✅ 插屏广告
  • ✅ 激励视频广告
  • ✅ 横幅广告
iOS:
  • ✅ 插屏广告
  • ✅ 激励视频广告
  • ✅ 横幅广告

安装

要将Yandex移动广告插件集成到基于Flutter的移动应用中,请在项目的pubspec.yaml文件中添加以下依赖:

dependencies:
  ...
  flutter_yandex_mobile_ads: ^0.0.12
重要提示(仅适用于iOS):

此插件版本0.0.9使用了YandexMobileAds版本5.4.0,该版本需要Swift 5.7才能正确构建。

使用

初始化

首先,初始化插件:

Yandex.initialize();
插屏广告
加载

创建一个监听器来处理插屏广告的加载事件:

listener(YandexAdEvent event, dynamic args) {
  if (event == YandexAdEvent.adReady) {
    interstitialLoaded = true;
  } else if (event == YandexAdEvent.adLoadFailed) {
    debugPrint("Failed to load Interstitial Ad");
  }
}

Yandex.interstititalListener = listener;
Yandex.loadInterstitial("R-M-DEMO-interstitial");

替换R-M-DEMO-interstitial为你的广告位密钥。

显示

当广告加载完成后,可以调用showInterstitial方法来显示插屏广告:

Yandex.showInterstitial();
激励视频广告
加载和显示

创建一个监听器来处理激励视频广告的加载事件:

var listener = (YandexAdEvent event, dynamic args) {
  if (event == YandexAdEvent.adReady) {
    Yandex.showRewardedVideo();
  } else if (event == YandexAdEvent.adLoadFailed) {
    debugPrint("Failed to load Rewarded Video");
  } else if (event == YandexAdEvent.adRewarded) {
    debugPrint("Successfully rewarded");
  }
};

Yandex.rewardedListener = listener;
Yandex.loadRewarded("R-M-DEMO-rewarded-client-side-rtb");

替换R-M-DEMO-rewarded-client-side-rtb为你的广告位密钥。

横幅广告

横幅广告可以通过两种方式设置大小:

YandexBanner(
  adUnitId: "R-M-DEMO-300x250",
  size: YandexBannerSize.stickySize(MediaQuery.of(context).size.width.toInt()),
)

或者

YandexBanner(
  adUnitId: "R-M-DEMO-300x250",
  size: YandexBannerSize.flexibleSize(320, 320),
)

示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用flutter_yandex_mobile_ads插件。

import 'package:flutter/material.dart';
import 'package:flutter_yandex_mobile_ads/banner.dart';
import 'package:flutter_yandex_mobile_ads/yandex.dart';
import 'package:flutter_yandex_mobile_ads_example/flex_banner_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String status = "尝试加载广告";

  bool interstitialLoaded = false;
  bool rewardedLoaded = false;

  [@override](/user/override)
  void initState() {
    super.initState();
    init();
  }

  void init() async {
    await Yandex.initialize();
    setState(() {});
  }

  void loadInterstitial() {
    setState(() {
      status = "正在加载插屏广告";
    });
    listener(YandexAdEvent event, dynamic args) {
      debugPrint("插屏广告: Yandex事件: $event");
      if (event == YandexAdEvent.adReady) {
        setState(() {
          interstitialLoaded = true;
          status = "插屏广告加载成功";
        });
      } else if (event == YandexAdEvent.adLoadFailed) {
        setState(() {
          status = "插屏广告加载失败: ${args['errorMessage']}";
        });
      }
    }

    Yandex.interstititalListener = listener;
    Yandex.loadInterstitial("R-M-DEMO-interstitial");
  }

  void showInterstitial() {
    if (interstitialLoaded) {
      setState(() {
        status = "正在显示插屏广告";
        interstitialLoaded = false;
        Yandex.showInterstitial();
      });
    }
  }

  void loadRewardedVideo() {
    setState(() {
      status = "正在加载激励视频广告";
    });
    var listener = (YandexAdEvent event, dynamic args) {
      if (event == YandexAdEvent.adReady) {
        setState(() {
          rewardedLoaded = true;
          status = "激励视频广告加载成功";
        });
      } else if (event == YandexAdEvent.adLoadFailed) {
        setState(() {
          status = "激励视频广告加载失败: ${args['errorMessage']}";
        });
      } else if (event == YandexAdEvent.adRewarded) {
        setState(() {
          status = "奖励已发放";
        });
      }
    };
    Yandex.rewardedListener = listener;
    Yandex.loadRewarded("R-M-DEMO-rewarded-client-side-rtb");
  }

  void showRewardedVideo() {
    if (rewardedLoaded) {
      setState(() {
        status = "正在显示激励视频广告";
        rewardedLoaded = false;
        Yandex.showRewardedVideo();
      });
    }
  }

  void openFlexBannerPage() {
    debugPrint("打开横幅页面");
    Navigator.of(context).push(MaterialPageRoute<void>(
      builder: (BuildContext context) {
        return FlexBannerPage(); // ... to here.
      },
    ));
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('Flutter Yandex Mobile Ads'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            TextButton(
                onPressed: loadInterstitial,
                child: Text("加载插屏广告")),
            TextButton(
                onPressed: showInterstitial,
                child: Text("显示插屏广告")),

            TextButton(
                onPressed: loadRewardedVideo,
                child: Text("加载激励视频广告")),
            TextButton(
                onPressed: showRewardedVideo,
                child: Text("显示激励视频广告")),
            TextButton(
                onPressed: openFlexBannerPage,
                child: Text("打开横幅页面")),

            Expanded(
                child: Container(
                    alignment: Alignment.center, child: Text(status))),
            Container(height: 2, color: Colors.green,),
            YandexBanner(
              adUnitId: "R-M-DEMO-300x250",
              size: YandexBannerSize.stickySize(width.toInt()),
              listener: (event, arguments) {
                switch(event) {
                  case YandexAdEvent.adReady:
                    setState(() {
                      status = "横幅广告加载成功";
                    });
                    break;
                  case YandexAdEvent.adLoadFailed:
                    setState(() {
                      status = "横幅广告加载失败: ${arguments['errorMessage']}";
                    });
                    break;
                  case YandexAdEvent.adClicked:
                    setState(() {
                      status = "横幅广告被点击";
                    });
                    break;
                }
              },
            ),
            Container(height: 2, color: Colors.green,)
          ],
        ),
      ),
    );
  }
}

class CustomButton extends StatelessWidget {
  final String label;
  final Function onPressed;

  const CustomButton({Key key, this.label, this.onPressed}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.0),
      child: MaterialButton(
        minWidth: 250.0,
        height: 50.0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(40.0),
            side: BorderSide(width: 2.0, color: Colors.blue)),
        child: Text(
          label.toUpperCase(),
          style: TextStyle(),
        ),
        onPressed: onPressed,
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中集成并使用flutter_yandex_mobile_ads插件的代码案例。这个插件允许你在Flutter应用中集成Yandex移动广告。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_yandex_mobile_ads: ^最新版本号  # 替换为最新的版本号

然后运行flutter pub get来获取依赖。

2. 配置Android和iOS项目

Android

android/app/src/main/AndroidManifest.xml中添加必要的权限和广告活动配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        ...>
        
        <!-- Yandex Mobile Ads SDK Configuration -->
        <meta-data
            android:name="com.yandex.mobile.ads.APP_ID"
            android:value="你的Yandex广告APP ID"/>

        <activity
            android:name="com.yandex.mobile.ads.AdActivity"
            android:configChanges="orientation|screenSize"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
            
        <!-- Other configurations -->
        
    </application>
</manifest>

iOS

ios/Runner/Info.plist中添加必要的配置:

<dict>
    ...
    <key>YandexMobileAdsAppId</key>
    <string>你的Yandex广告APP ID</string>
    ...
</dict>

然后,在ios/Podfile中添加以下行以确保使用Swift版本(如果需要):

platform :ios, '10.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Release' => :release,
  'Profile' => :release,
}

target 'Runner' do
  # Flutter Pod
  use_frameworks!
  config = use_native_modules!

  # Add Yandex Mobile Ads SDK pod
  pod 'YandexMobileAds', '~> 最新版本号'  # 替换为最新的版本号

  # Enable Swift and Objective-C interoperability
  config.build_settings['SWIFT_OBJC_BRIDGING_HEADER'] = '$(SRCROOT)/Runner/Bridging-Header.h'
  config.build_settings['DEFINES_MODULE'] = 'YES'

  # Flutter dependencies
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

3. 初始化并使用广告

在你的Dart代码中,初始化Yandex广告并展示一个横幅广告:

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化Yandex广告SDK
  YandexMobileAds.instance.initialize(
    appId: '你的Yandex广告APP ID',
    testMode: true,  // 如果在测试模式下,设置为true
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Yandex Mobile Ads Example'),
        ),
        body: Center(
          child: BannerAdWidget(
            adUnitId: '你的横幅广告单元ID',
            // 其他配置参数
            size: AdSize.banner,
            listener: (AdEvent event, Map<String, dynamic> info) {
              print('Ad event: $event, info: $info');
            },
          ),
        ),
      ),
    );
  }
}

4. 运行应用

确保你已经正确配置了所有必要的步骤,然后运行你的Flutter应用:

flutter run

这段代码展示了如何在Flutter应用中集成Yandex移动广告的基本步骤。根据你的需求,你可能需要调整配置和代码以适应具体的广告格式和展示策略。

回到顶部