Flutter广告发布插件adspostx_flutter的使用

Flutter广告发布插件adspostx_flutter的使用

AdsPostX 提供了一个 Flutter 插件,旨在帮助你在 Flutter 移动应用中集成 AdsPostX,并在几分钟内开始生成更多收入和增加销售。

集成指南

请访问 https://docs.adspostx.com/flutter-sdk 以获取有关将 adspostx_flutter 插件集成到你的 Flutter 应用中的所有详细信息。

使用

初始化 AdsPostX

sdkId 必须是一个有效的 SDK ID。

Future<void> init(String sdkId, BuildContext context) async {
  bool status = false;
  // 显示一些加载指示器...
  try {
    status = await _adspostxPlugin.init(sdkId);
    // 隐藏加载指示器,如果 status 为 true,意味着我们已经准备好加载广告了。
  } on PlatformException catch (error) {
    // 隐藏加载指示器,并优雅地处理错误。
  }
}

加载广告

如果你不想传递任何属性,则传递 {}

Future<void> loadOffers(Map attributes, BuildContext context) async {
  bool status = false;
  // 显示加载指示器..
  // 如果不需要任何属性,传递 {}

  try {
    status = await _adspostxPlugin.loadOffers(attributes);
    // 隐藏加载指示器,如果 status 为 true,意味着我们可以展示广告了。
  } on PlatformException catch (error) {
    // 隐藏加载指示器,并优雅地处理错误。
  }
}

展示广告

  • presentationStyle = 0 - 弹窗
  • presentationStyle = 1 - 全屏
  • topMargin, rightMargin, bottomMargin, leftMargin 的值应在 0 到 15 之间。
Future<void> showOffers(int presentationStyle, bool isTransparent,
    int topMargin, int rightMargin, int bottomMargin, int leftMargin) async {
  bool status = false;
  try {
    status = await _adspostxPlugin.showOffers(
        presentationStyle,
        isTransparent,
        topMargin,
        rightMargin,
        bottomMargin,
        leftMargin, (dismissStatus) {
      print("Offer dismiss status is: $dismissStatus");
    });
    print("show offers status: $status");
  } on PlatformException catch (error) {
    // utility.showAlert(error.message as String);
  }
}

设置环境

  • environment = 0 - 生产环境
  • environment = 1 - 测试环境
Future<void> setEnvironment(int environment) async {
  // 环境必须是 0 或 1。0 - 生产环境,1 - 测试环境。
  bool status = false;
  try {
    status = await _adspostxPlugin.setEnvironment(environment);
    print("setEnvironment status: $status");
  } on PlatformException catch (error) {
    print(error.message as String);
  }
}

启用调试日志

Future<void> enableDebugLog(bool shouldEnable) async {
  bool status = false;
  try {
    status = await _adspostxPlugin.enableDebugLog(shouldEnable);
    print("enableDebugLog status: $status");
  } on PlatformException catch (error) {
    print(error.message as String);
  }
}

完整示例 Demo

以下是一个完整的示例 Demo,展示了如何使用 adspostx_flutter 插件:

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(home: AdsPostXDemo());
  }
}

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

class _AdsPostXDemoState extends State<AdsPostXDemo> {
  final _adspostxPlugin = AdsPostXPlugin();

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

  Future<void> _initAdspostx() async {
    try {
      bool status = await _adspostxPlugin.init('YOUR_SDK_ID', context);
      if (status) {
        print('AdsPostX initialized successfully');
      } else {
        print('Failed to initialize AdsPostX');
      }
    } catch (e) {
      print('Error initializing AdsPostX: $e');
    }
  }

  void _loadOffers() async {
    try {
      bool status = await _adspostxPlugin.loadOffers({}, context);
      if (status) {
        print('Offers loaded successfully');
      } else {
        print('Failed to load offers');
      }
    } catch (e) {
      print('Error loading offers: $e');
    }
  }

  void _showOffers() async {
    try {
      bool status = await _adspostxPlugin.showOffers(
          0, // presentationStyle
          false, // isTransparent
          5, // topMargin
          5, // rightMargin
          5, // bottomMargin
          5); // leftMargin
      if (status) {
        print('Offers shown successfully');
      } else {
        print('Failed to show offers');
      }
    } catch (e) {
      print('Error showing offers: $e');
    }
  }

  void _setEnvironment() async {
    try {
      bool status = await _adspostxPlugin.setEnvironment(1); // 0 for LIVE, 1 for TEST
      if (status) {
        print('Environment set successfully');
      } else {
        print('Failed to set environment');
      }
    } catch (e) {
      print('Error setting environment: $e');
    }
  }

  void _enableDebugLog() async {
    try {
      bool status = await _adspostxPlugin.enableDebugLog(true);
      if (status) {
        print('Debug log enabled successfully');
      } else {
        print('Failed to enable debug log');
      }
    } catch (e) {
      print('Error enabling debug log: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AdsPostX Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _loadOffers,
              child: Text('Load Offers'),
            ),
            ElevatedButton(
              onPressed: _showOffers,
              child: Text('Show Offers'),
            ),
            ElevatedButton(
              onPressed: _setEnvironment,
              child: Text('Set Environment'),
            ),
            ElevatedButton(
              onPressed: _enableDebugLog,
              child: Text('Enable Debug Log'),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


adspostx_flutter 是一个用于在 Flutter 应用中集成广告的插件。它支持多种广告平台,如 Google AdMob、Facebook Audience Network 等,并且提供了简单易用的 API 来展示横幅广告、插页式广告、激励视频广告等。

安装

首先,你需要在 pubspec.yaml 文件中添加 adspostx_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  adspostx_flutter: ^latest_version

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

初始化

在使用 adspostx_flutter 插件之前,你需要在应用的 main 函数中进行初始化。通常在 WidgetsFlutterBinding.ensureInitialized() 之后进行:

import 'package:adspostx_flutter/adspostx_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化广告插件
  await AdspostxFlutter.initialize(
    appId: 'YOUR_ADMOB_APP_ID',
    // 其他配置参数
  );
  
  runApp(MyApp());
}

展示横幅广告

要展示横幅广告,你可以使用 BannerAd 组件。首先,你需要创建一个 BannerAd 实例,然后将其添加到你的 UI 中:

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

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

class _MyHomePageState extends State<MyHomePage> {
  late BannerAd _bannerAd;

  [@override](/user/override)
  void initState() {
    super.initState();
    
    // 创建横幅广告实例
    _bannerAd = BannerAd(
      adUnitId: 'YOUR_BANNER_AD_UNIT_ID',
      size: AdSize.banner,
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) => print('Ad loaded.'),
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          ad.dispose();
          print('Ad failed to load: $error');
        },
        onAdOpened: (Ad ad) => print('Ad opened.'),
        onAdClosed: (Ad ad) => print('Ad closed.'),
      ),
    );
    
    // 加载广告
    _bannerAd.load();
  }

  [@override](/user/override)
  void dispose() {
    _bannerAd.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Ads Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Hello, World!',
            ),
            // 展示横幅广告
            Container(
              alignment: Alignment.center,
              width: _bannerAd.size.width.toDouble(),
              height: _bannerAd.size.height.toDouble(),
              child: AdWidget(ad: _bannerAd),
            ),
          ],
        ),
      ),
    );
  }
}

展示插页式广告

要展示插页式广告,你可以使用 InterstitialAd 类。首先,你需要加载插页式广告,然后在适当的时机展示它:

import 'package:adspostx_flutter/adspostx_flutter.dart';

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

class _MyHomePageState extends State<MyHomePage> {
  InterstitialAd? _interstitialAd;

  [@override](/user/override)
  void initState() {
    super.initState();
    
    // 加载插页式广告
    InterstitialAd.load(
      adUnitId: 'YOUR_INTERSTITIAL_AD_UNIT_ID',
      request: AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (InterstitialAd ad) {
          _interstitialAd = ad;
          _interstitialAd!.setFullScreenContentCallback(FullScreenContentCallback(
            onAdDismissedFullScreenContent: (InterstitialAd ad) {
              ad.dispose();
            },
            onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
              ad.dispose();
            },
          ));
        },
        onAdFailedToLoad: (LoadAdError error) {
          print('InterstitialAd failed to load: $error');
        },
      ),
    );
  }

  void _showInterstitialAd() {
    if (_interstitialAd != null) {
      _interstitialAd!.show();
    } else {
      print('InterstitialAd is not ready yet.');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Ads Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _showInterstitialAd,
          child: Text('Show Interstitial Ad'),
        ),
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    _interstitialAd?.dispose();
    super.dispose();
  }
}

展示激励视频广告

要展示激励视频广告,你可以使用 RewardedAd 类。首先,你需要加载激励视频广告,然后在适当的时机展示它:

import 'package:adspostx_flutter/adspostx_flutter.dart';

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

class _MyHomePageState extends State<MyHomePage> {
  RewardedAd? _rewardedAd;

  [@override](/user/override)
  void initState() {
    super.initState();
    
    // 加载激励视频广告
    RewardedAd.load(
      adUnitId: 'YOUR_REWARDED_AD_UNIT_ID',
      request: AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(
        onAdLoaded: (RewardedAd ad) {
          _rewardedAd = ad;
          _rewardedAd!.setFullScreenContentCallback(FullScreenContentCallback(
            onAdDismissedFullScreenContent: (RewardedAd ad) {
              ad.dispose();
            },
            onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
              ad.dispose();
            },
          ));
        },
        onAdFailedToLoad: (LoadAdError error) {
          print('RewardedAd failed to load: $error');
        },
      ),
    );
  }

  void _showRewardedAd() {
    if (_rewardedAd != null) {
      _rewardedAd!.show(onUserEarnedReward: (RewardedAd ad, RewardItem reward) {
        print('User earned reward: ${reward.amount} ${reward.type}');
      });
    } else {
      print('RewardedAd is not ready yet.');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Ads Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _showRewardedAd,
          child: Text('Show Rewarded Ad'),
        ),
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    _rewardedAd?.dispose();
    super.dispose();
  }
}
回到顶部