Flutter广告展示插件notix_ads的使用

Flutter广告展示插件notix_ads的使用

该原生插件允许您展示由Notix提供的横幅广告和应用打开广告。这是一个定制脚本,因为Notix尚未为Flutter官方发布横幅和应用打开广告。

安装

在您的 pubspec.yaml 文件中添加以下行:

dependencies:
  notix_ads: ^x.y.z

x.y.z 替换为您从 pub.dev 上获取的最新版本号。然后导入插件:

import 'package:notix_ads/notix_ads.dart';

开始使用

1. 初始化横幅广告

首先我们需要加载横幅广告以便于展示。有三种横幅广告尺寸可供使用:

enum BannerAdSize {
  standard, // 320/50
  landscape, // 320/90
  rectangle, // 320/250
}

您可以调用 NotixAds.loadBanner 来加载横幅广告:

late Widget banner;
void initState() {
  banner = await NotixAds().loadBanner( /*Your Zone ID*/, BannerAdSize.landscape);
}

// 然后可以在任何地方使用 `banner` 来加载它。

2. 展示应用打开广告

您可以使用 didChangeAppLifecycleState 检查应用程序状态并调用应用打开广告:

[@override](/user/override)
void didChangeAppLifecycleState(AppLifecycleState state) {
  if (state == AppLifecycleState.paused) {
    NotixAds().appOpen(/*Your Zone ID*/);
  }
}

3. 展示通知广告

通过调用 NotixAds().NotificationInit 并传入您的 notixAppIdnotixToken 来初始化通知广告。这些凭据可以在您的In-App Android源页面上找到:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  NotixAds().NotificationInit(/* notixAppId */, /* notixToken */);
  runApp(const MyApp());
}

4. 展示插屏广告

您可以使用 NotixAds().interstitial 来展示插屏广告。这将在一行代码中加载并展示广告:

NotixAds().interstitial(/*Your Zone ID*/);

完整示例代码

以下是完整的示例代码,展示了如何在Flutter应用中使用 notix_ads 插件:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:notix_ads/notix_ads.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  NotixAds().NotificationInit('p6xxxx', 'cxxxc7744fa847f4a59f7beac9fxxxx');
  runApp(const MyApp());
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Widget? _banner;
  final _notixAdsPlugin = NotixAds();

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

  // 异步平台消息初始化
  Future<void> initPlatformState() async {
    // 尝试加载横幅广告
    try {
      _banner = await _notixAdsPlugin.loadBanner(0000) ?? Text("Fail to load banner");
    } on PlatformException {
      // 处理错误情况
      print('Failed to get platform version.');
    }

    // 如果组件被移除,则不更新UI
    if (!mounted) return;

    setState(() {});
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: _banner,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            // _notixAdsPlugin.appOpen(xxxx);
            _notixAdsPlugin.interstitial(0000);
          },
        ),
      ),
    );
  }
}

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

1 回复

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


notix_ads 是一个用于在 Flutter 应用中展示广告的插件。它通常用于集成不同类型的广告(如横幅广告、插页式广告、激励视频广告等)。以下是如何在 Flutter 项目中使用 notix_ads 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  notix_ads: ^1.0.0  # 请使用最新版本

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

2. 初始化广告插件

在你的应用启动时,你需要在 main.dart 文件中初始化 notix_ads 插件。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化广告插件
  await NotixAds.initialize(
    appId: 'YOUR_APP_ID',  // 替换为你的应用ID
    isDebug: true,         // 调试模式
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 展示横幅广告

你可以在应用的任何页面中展示横幅广告。以下是一个简单的示例:

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

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

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

  @override
  void initState() {
    super.initState();
    _bannerAd = BannerAd(
      adUnitId: 'YOUR_BANNER_AD_UNIT_ID',  // 替换为你的横幅广告单元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
  void dispose() {
    _bannerAd.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Banner Ad Example',
            ),
            Container(
              alignment: Alignment.center,
              child: AdWidget(ad: _bannerAd),
              width: _bannerAd.size.width.toDouble(),
              height: _bannerAd.size.height.toDouble(),
            ),
          ],
        ),
      ),
    );
  }
}

4. 展示插页式广告

你可以在用户执行某些操作(如点击按钮)后展示插页式广告。

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

class InterstitialAdExample extends StatefulWidget {
  @override
  _InterstitialAdExampleState createState() => _InterstitialAdExampleState();
}

class _InterstitialAdExampleState extends State<InterstitialAdExample> {
  InterstitialAd? _interstitialAd;

  @override
  void initState() {
    super.initState();
    _loadInterstitialAd();
  }

  void _loadInterstitialAd() {
    InterstitialAd.load(
      adUnitId: 'YOUR_INTERSTITIAL_AD_UNIT_ID',  // 替换为你的插页式广告单元ID
      request: AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (InterstitialAd ad) {
          _interstitialAd = ad;
          _interstitialAd?.setFullScreenContentCallback(FullScreenContentCallback(
            onAdDismissedFullScreenContent: (InterstitialAd ad) {
              ad.dispose();
              _loadInterstitialAd();
            },
            onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
              ad.dispose();
              _loadInterstitialAd();
            },
          ));
        },
        onAdFailedToLoad: (LoadAdError error) {
          print('InterstitialAd failed to load: $error');
        },
      ),
    );
  }

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

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

5. 展示激励视频广告

激励视频广告通常用于奖励用户观看广告。

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

class RewardedAdExample extends StatefulWidget {
  @override
  _RewardedAdExampleState createState() => _RewardedAdExampleState();
}

class _RewardedAdExampleState extends State<RewardedAdExample> {
  RewardedAd? _rewardedAd;

  @override
  void initState() {
    super.initState();
    _loadRewardedAd();
  }

  void _loadRewardedAd() {
    RewardedAd.load(
      adUnitId: 'YOUR_REWARDED_AD_UNIT_ID',  // 替换为你的激励视频广告单元ID
      request: AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(
        onAdLoaded: (RewardedAd ad) {
          _rewardedAd = ad;
          _rewardedAd?.setFullScreenContentCallback(FullScreenContentCallback(
            onAdDismissedFullScreenContent: (RewardedAd ad) {
              ad.dispose();
              _loadRewardedAd();
            },
            onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
              ad.dispose();
              _loadRewardedAd();
            },
          ));
        },
        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 not ready yet.');
    }
  }

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

6. 处理广告生命周期

确保在页面销毁时释放广告资源,以避免内存泄漏。

@override
void dispose() {
  _bannerAd.dispose();
  _interstitialAd?.dispose();
  _rewardedAd?.dispose();
  super.dispose();
}

7. 测试广告

在开发阶段,你可以使用测试广告单元ID来测试广告的展示效果。

  • 横幅广告测试ID: ca-app-pub-3940256099942544/6300978111
  • 插页式广告测试ID: ca-app-pub-3940256099942544/1033173712
  • 激励视频广告测试ID: ca-app-pub-3940256099942544/5224354917

8. 发布应用

在发布应用之前,确保将测试广告单元ID替换为真实的广告单元ID,并关闭调试模式。

await NotixAds.initialize(
  appId: 'YOUR_APP_ID',
  isDebug: false,  // 生产环境关闭调试模式
);
回到顶部