Flutter广告集成插件adivery的使用

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

Flutter广告集成插件adivery的使用

adivery 是一个简单的 Flutter 插件,可以激活 Flutter 应用中的 Adivery 广告。

完整示例代码

import 'package:adivery/adivery.dart';
import 'package:adivery/adivery_ads.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static late _MyAppState instance;

  @override
  void initState() {
    super.initState();
    initPlatformState();
    instance = this;
  }

  void initPlatformState() {
    // 初始化 Adivery 插件,并设置广告位 ID 和日志开关
    AdiveryPlugin.initialize("7e27fb38-5aff-473a-998f-437b89426f66");
    AdiveryPlugin.setLoggingEnabled(true);
    AdiveryPlugin.prepareInterstitialAd("de5db046-765d-478f-bb2e-30dc2eaf3f51");
    AdiveryPlugin.prepareRewardedAd("3f97dc4d-3e09-4024-acaf-931862c03ba8");
    AdiveryPlugin.addListener(
      onError: onError,
      onInterstitialLoaded: onInterstitialLoaded,
      onRewardedClosed: onRewardedClosed,
      onRewardedLoaded: (placement) {},
    );
  }

  static void onInterstitialLoaded(String placement) {
    print("interstitial loaded");
  }

  static void onRewardedClosed(String placement, bool isRewarded) {
    print("ad rewarded: " + isRewarded.toString());
    if (isRewarded) {
      instance.setState(() {
        instance._reward += 1;
      });
    }
  }

  static void onError(String placement, String error) {
    print("onError" + error);
  }

  static void _onAdLoaded(Ad ad) {
    print("banner loaded");
  }

  static void _onAdClicked(Ad ad) {
    print("banner clicked");
  }

  static void _onError(Ad ad, String error) {
    print("banner load failed " + error);
  }

  static int _index = 0;

  int _reward = 0;

  NativeAd? nativeAd;

  List<Widget> _widgetOptions = [
    Row(
      children: [
        BannerAd(
          "2f71ec44-f30a-4043-9cc1-f32347a07f8b",
          BannerAdSize.BANNER,
          onAdLoaded: _onAdLoaded,
          onAdClicked: _onAdClicked,
        ),
      ],
    ),
    Row(
      children: [
        BannerAd(
          "2f71ec44-f30a-4043-9cc1-f32347a07f8b",
          BannerAdSize.LARGE_BANNER,
          onAdLoaded: _onAdLoaded,
          onAdClicked: _onAdClicked,
          onError: _onError,
        ),
      ],
    ),
    Row(
      children: [
        BannerAd(
          "2f71ec44-f30a-4043-9cc1-f32347a07f8b",
          BannerAdSize.MEDIUM_RECTANGLE,
          onAdLoaded: _onAdLoaded,
          onAdClicked: _onAdClicked,
          onError: _onError,
        ),
      ],
    ),
  ];

  void _onChanged(int index) {
    setState(() {
      _index = index;
    });
  }

  Widget _getBanner() {
    if (_index == 0) {
      return _widgetOptions.elementAt(0);
    } else if (_index == 1) {
      return BannerAd(
        "2f71ec44-f30a-4043-9cc1-f32347a07f8b",
        BannerAdSize.LARGE_BANNER,
        onAdLoaded: _onAdLoaded,
        onAdClicked: _onAdClicked,
        onError: _onError,
      );
    } else {
      return _widgetOptions.elementAt(2);
    }
  }

  _loadInterstitial() {
    var placementId = "de5db046-765d-478f-bb2e-30dc2eaf3f51";
    AdiveryPlugin.isLoaded(placementId)
        .then((isLoaded) => showPlacement(isLoaded!, placementId));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Adivery 示例应用'),
            ),
            body: Center(
              child: Container(
                child: Column(
                  children: [
                    Center(
                      child: Text("你的奖励积分是: $_reward"),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Flexible(
                          flex: 1,
                          fit: FlexFit.tight,
                          child: ElevatedButton(
                            child: Text("横幅广告"),
                            onPressed: () {
                              _onChanged(0);
                            },
                          ),
                        ),
                        Flexible(
                          flex: 1,
                          child: ElevatedButton(
                            child: Text("大横幅广告"),
                            onPressed: () {
                              _onChanged(1);
                            },
                          ),
                        ),
                        Flexible(
                          flex: 1,
                          child: ElevatedButton(
                            child: Text("中矩形广告"),
                            onPressed: () {
                              _onChanged(2);
                            },
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [_getBanner()],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Flexible(
                          child: ElevatedButton(
                            onPressed: _loadInterstitial,
                            child: Text("插屏广告"),
                          ),
                        ),
                        Flexible(
                          child: ElevatedButton(
                            onPressed: _loadRewardedAd,
                            child: Text("激励视频广告"),
                          ),
                        ),
                        Flexible(
                          child: ElevatedButton(
                            onPressed: _loadNative,
                            child: Text("原生广告"),
                          ),
                        ),
                      ],
                    ),
                    _nativeAd()
                  ],
                ),
              ),
            )));
  }

  void _loadRewardedAd() {
    var placementId = "3f97dc4d-3e09-4024-acaf-931862c03ba8";
    AdiveryPlugin.isLoaded(placementId)
        .then((isLoaded) => showPlacement(isLoaded!, placementId));
  }

  Widget _nativeAd() {
    if (nativeAd != null && nativeAd!.isLoaded) {
      return Column(
        children: [
          Row(
              mainAxisAlignment: MainAxisAlignment.end,
              mainAxisSize: MainAxisSize.max,
              children: [
                Flexible(
                  flex: 2,
                  child: Column(children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Flexible(
                          flex: 1,
                          child: ElevatedButton(
                            onPressed: () {
                              nativeAd!.recordClick();
                            },
                            child: Text(nativeAd!.callToAction!),
                          ),
                        ),
                        Flexible(
                          flex: 2,
                          child: Text(
                            nativeAd!.headline!,
                            style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                                fontSize: 16),
                            textAlign: TextAlign.end,
                          ),
                        )
                      ],
                    ),
                    Text(
                      nativeAd!.description!,
                      textAlign: TextAlign.end,
                    )
                  ]),
                ),
                Flexible(
                  flex: 1,
                  fit: FlexFit.loose,
                  child: Column(
                    children: [
                      nativeAd!.icon!,
                      Text(nativeAd!.advertiser!)
                    ],
                  ),
                ),
              ]),
          nativeAd!.image!,
        ],
      );
    } else {
      return Container();
    }
  }

  void _loadNative() {
    nativeAd = new NativeAd(
      "25928bf1-d4f7-432c-aaf7-1780602796c3",
      onAdLoaded: _onNativeAdLoaded,
    );
    nativeAd!.loadAd();
    // 当 Widget 移除时调用 nativeAd.destroy();
  }

  void _onNativeAdLoaded() {
    setState(() {});
  }

  void showPlacement(bool isLoaded, String placementId) {
    if (isLoaded) {
      AdiveryPlugin.show(placementId);
    }
  }
}

代码说明

  1. 初始化插件

    AdiveryPlugin.initialize("7e27fb38-5aff-473a-998f-437b89426f66");
    AdiveryPlugin.setLoggingEnabled(true);
    

    这里初始化了 Adivery 插件,并设置了日志开关。

  2. 准备广告位

    AdiveryPlugin.prepareInterstitialAd("de5db046-765d-478f-bb2e-30dc2eaf3f51");
    AdiveryPlugin.prepareRewardedAd("3f97dc4d-3e09-4024-acaf-931862c03ba8");
    

    准备插屏广告和激励视频广告。

  3. 添加监听器

    AdiveryPlugin.addListener(
      onError: onError,
      onInterstitialLoaded: onInterstitialLoaded,
      onRewardedClosed: onRewardedClosed,
      onRewardedLoaded: (placement) {},
    );
    

    添加错误处理、插屏广告加载完成、激励视频广告关闭和加载完成的监听器。

  4. 加载并显示广告

    _loadInterstitial() {
      var placementId = "de5db046-765d-478f-bb2e-30dc2eaf3f51";
      AdiveryPlugin.isLoaded(placementId)
          .then((isLoaded) => showPlacement(isLoaded!, placementId));
    }
    

    检查插屏广告是否加载完成,并显示广告。

  5. 处理原生广告

    void _loadNative() {
      nativeAd = new NativeAd(
        "25928bf1-d4f7-432c-aaf7-1780602796c3",
        onAdLoaded: _onNativeAdLoaded,
      );
      nativeAd!.loadAd();
      // 当 Widget 移除时调用 nativeAd.destroy();
    }
    

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中集成并使用Adivery广告插件的示例代码。Adivery是一个流行的广告平台,它提供了多种广告格式,比如横幅广告、插屏广告和原生广告等。在Flutter中,你可以通过其官方提供的SDK来集成广告。

首先,确保你已经在Flutter项目中添加了Adivery的依赖。在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  adivery_flutter: ^latest_version  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

接下来,你需要在你的Flutter应用中初始化Adivery,并展示广告。以下是一个简单的示例,展示了如何集成横幅广告和插屏广告。

1. 初始化Adivery

在你的应用的主入口文件(通常是main.dart)中,初始化Adivery SDK。

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化Adivery
  AdiveryFlutter.instance.init(
    appId: 'YOUR_APP_ID', // 替换为你的Adivery应用ID
    testMode: true, // 如果是开发环境,设置为true;生产环境设置为false
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

2. 展示横幅广告

创建一个横幅广告小部件,并在你的页面中使用它。

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  BannerAd? _bannerAd;

  @override
  void initState() {
    super.initState();
    // 加载横幅广告
    _loadBannerAd();
  }

  void _loadBannerAd() {
    BannerAd.createBannerAd(
      adUnitId: 'YOUR_BANNER_AD_UNIT_ID', // 替换为你的横幅广告单元ID
      adSize: AdSize.banner, // 横幅尺寸,可以选择其他尺寸如AdSize.largeBanner等
      listener: (AdEvent event, Map<String, dynamic>? info) {
        // 广告事件回调,可以在这里处理广告加载成功、失败、点击等事件
        print('BannerAd event is $event');
      },
    ).then((bannerAd) {
      setState(() {
        _bannerAd = bannerAd;
      });
    }).catchError((error) {
      print('Failed to load banner ad: $error');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Adivery Flutter Integration'),
      ),
      body: Center(
        child: _bannerAd != null
            ? Container(
                margin: EdgeInsets.only(bottom: 20.0),
                child: AdWidget(ad: _bannerAd!),
              )
            : CircularProgressIndicator(), // 加载中的指示器
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 展示插屏广告
          _showInterstitialAd();
        },
        tooltip: 'Show Interstitial',
        child: Icon(Icons.add),
      ),
    );
  }

  void _showInterstitialAd() {
    InterstitialAd.loadInterstitialAd(
      adUnitId: 'YOUR_INTERSTITIAL_AD_UNIT_ID', // 替换为你的插屏广告单元ID
      listener: (AdEvent event, Map<String, dynamic>? info) {
        // 广告事件回调
        if (event == AdEvent.loaded) {
          // 广告加载成功后展示
          InterstitialAd.instance.show();
        }
      },
    ).catchError((error) {
      print('Failed to load interstitial ad: $error');
    });
  }
}

3. 运行应用

确保你已经替换了所有的占位符(如YOUR_APP_ID, YOUR_BANNER_AD_UNIT_ID, YOUR_INTERSTITIAL_AD_UNIT_ID)为你的实际Adivery应用ID和广告单元ID。然后运行你的Flutter应用,你应该能够看到横幅广告和插屏广告的展示。

请注意,在实际发布应用之前,确保将testMode设置为false,并在Adivery平台上配置好所有必要的广告单元和广告创意。

回到顶部