メインコンテンツへスキップ

概要

Adrop Flutter SDKのサンプルコードとサンプルプロジェクトをご確認ください。

サンプルプロジェクト

GitHubで完全なサンプルプロジェクトを確認できます。

Flutterサンプルプロジェクト

Dartで書かれたFlutterサンプルアプリ

クイックスタート例

バナー広告

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

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

  @override
  State<BannerAdExample> createState() => _BannerAdExampleState();
}

class _BannerAdExampleState extends State<BannerAdExample> {
  bool isLoaded = false;
  late AdropBannerView bannerView;

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

    bannerView = AdropBannerView(
      unitId: 'PUBLIC_TEST_UNIT_ID_320_100',
      listener: AdropBannerListener(
        onAdReceived: (unitId, metadata) {
          debugPrint('バナー広告受信成功: $unitId');
          setState(() => isLoaded = true);
        },
        onAdClicked: (unitId, metadata) {
          debugPrint('バナー広告クリック: $unitId');
        },
        onAdFailedToReceive: (unitId, errorCode) {
          debugPrint('バナー広告受信失敗: $errorCode');
        },
      ),
    );

    bannerView.load();
  }

  @override
  void dispose() {
    bannerView.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('バナー広告')),
      body: Column(
        children: [
          Expanded(
            child: Center(child: const Text('メインコンテンツ')),
          ),
          if (isLoaded)
            SizedBox(
              width: MediaQuery.of(context).size.width,
              height: 80,
              child: bannerView,
            ),
        ],
      ),
    );
  }
}

ネイティブ広告

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

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

  @override
  State<NativeAdExample> createState() => _NativeAdExampleState();
}

class _NativeAdExampleState extends State<NativeAdExample> {
  bool isLoaded = false;
  AdropNativeAd? nativeAd;

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

    nativeAd = AdropNativeAd(
      unitId: 'PUBLIC_TEST_UNIT_ID_NATIVE',
      listener: AdropNativeListener(
        onAdReceived: (ad) {
          debugPrint('ネイティブ広告受信: ${ad.creativeId}');
          setState(() => isLoaded = true);
        },
        onAdClicked: (ad) {
          debugPrint('ネイティブ広告クリック');
        },
        onAdFailedToReceive: (ad, errorCode) {
          debugPrint('ネイティブ広告受信失敗: $errorCode');
        },
      ),
    );

    nativeAd?.load();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('ネイティブ広告')),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const Padding(
              padding: EdgeInsets.all(16),
              child: Text('メインコンテンツ'),
            ),
            if (isLoaded) _buildNativeAdView(),
          ],
        ),
      ),
    );
  }

  Widget _buildNativeAdView() {
    return AdropNativeAdView(
      ad: nativeAd,
      child: Container(
        margin: const EdgeInsets.all(16),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.shade300),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // プロフィール
            Row(
              children: [
                if (nativeAd?.properties.profile?.displayLogo != null)
                  ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: Image.network(
                      nativeAd!.properties.profile!.displayLogo!,
                      width: 24,
                      height: 24,
                    ),
                  ),
                const SizedBox(width: 8),
                Text(
                  nativeAd?.properties.profile?.displayName ?? '',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            // ヘッドライン
            if (nativeAd?.properties.headline != null)
              Text(
                nativeAd!.properties.headline!,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            const SizedBox(height: 4),
            // 本文
            if (nativeAd?.properties.body != null)
              Text(
                nativeAd!.properties.body!,
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.grey,
                ),
              ),
            const SizedBox(height: 12),
            // 画像
            if (nativeAd?.properties.asset != null)
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  nativeAd!.properties.asset!,
                  width: double.infinity,
                  fit: BoxFit.cover,
                ),
              ),
            const SizedBox(height: 12),
            // CTAボタン
            if (nativeAd?.properties.callToAction != null)
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () {},
                  child: Text(nativeAd!.properties.callToAction!),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

インタースティシャル広告

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

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

  @override
  State<InterstitialAdExample> createState() => _InterstitialAdExampleState();
}

class _InterstitialAdExampleState extends State<InterstitialAdExample> {
  bool isLoaded = false;
  AdropInterstitialAd? interstitialAd;

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

  void _createInterstitialAd() {
    interstitialAd?.dispose();
    interstitialAd = AdropInterstitialAd(
      unitId: 'PUBLIC_TEST_UNIT_ID_INTERSTITIAL',
      listener: AdropInterstitialListener(
        onAdReceived: (ad) {
          debugPrint('インタースティシャル広告読み込み完了');
          setState(() => isLoaded = true);
        },
        onAdClicked: (ad) {
          debugPrint('インタースティシャル広告クリック');
        },
        onAdDidPresentFullScreen: (ad) {
          debugPrint('インタースティシャル広告表示');
        },
        onAdDidDismissFullScreen: (ad) {
          debugPrint('インタースティシャル広告閉じる');
          // 新しい広告を読み込む
          _createInterstitialAd();
          interstitialAd?.load();
        },
        onAdFailedToReceive: (ad, errorCode) {
          debugPrint('インタースティシャル広告読み込み失敗: $errorCode');
        },
      ),
    );

    setState(() => isLoaded = false);
  }

  @override
  void dispose() {
    interstitialAd?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('インタースティシャル広告')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => interstitialAd?.load(),
              child: const Text('広告を読み込む'),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: isLoaded ? () => interstitialAd?.show() : null,
              child: const Text('広告を表示'),
            ),
          ],
        ),
      ),
    );
  }
}

リワード広告

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

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

  @override
  State<RewardedAdExample> createState() => _RewardedAdExampleState();
}

class _RewardedAdExampleState extends State<RewardedAdExample> {
  bool isLoaded = false;
  int coins = 0;
  AdropRewardedAd? rewardedAd;

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

  void _createRewardedAd() {
    rewardedAd?.dispose();
    rewardedAd = AdropRewardedAd(
      unitId: 'PUBLIC_TEST_UNIT_ID_REWARDED',
      listener: AdropRewardedListener(
        onAdReceived: (ad) {
          debugPrint('リワード広告読み込み完了');
          setState(() => isLoaded = true);
        },
        onAdDidDismissFullScreen: (ad) {
          debugPrint('リワード広告閉じる');
          // 新しい広告を読み込む
          _createRewardedAd();
          rewardedAd?.load();
        },
        onAdEarnRewardHandler: (ad, type, amount) {
          debugPrint('報酬獲得: type=$type, amount=$amount');
          setState(() => coins += amount);
          _showRewardSnackBar(amount);
        },
        onAdFailedToReceive: (ad, errorCode) {
          debugPrint('リワード広告読み込み失敗: $errorCode');
        },
      ),
    );

    setState(() => isLoaded = false);
  }

  void _showRewardSnackBar(int amount) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('$amountコインを獲得しました!'),
        backgroundColor: Colors.green,
      ),
    );
  }

  @override
  void dispose() {
    rewardedAd?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('リワード広告')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // コイン表示
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.amber.shade100,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.monetization_on, color: Colors.amber),
                  const SizedBox(width: 8),
                  Text(
                    '$coinsコイン',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 32),
            ElevatedButton(
              onPressed: () => rewardedAd?.load(),
              child: const Text('広告を読み込む'),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: isLoaded ? () => rewardedAd?.show() : null,
              icon: const Icon(Icons.play_circle_outline),
              label: const Text('広告を見て報酬を獲得'),
              style: ElevatedButton.styleFrom(
                backgroundColor: isLoaded ? Colors.green : Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

ポップアップ広告

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

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

  @override
  State<PopupAdExample> createState() => _PopupAdExampleState();
}

class _PopupAdExampleState extends State<PopupAdExample> {
  bool isLoaded = false;
  AdropPopupAd? popupAd;

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

  void _createPopupAd() {
    popupAd?.dispose();
    popupAd = AdropPopupAd(
      unitId: 'PUBLIC_TEST_UNIT_ID_POPUP_BOTTOM',
      closeTextColor: Colors.white,
      hideForTodayTextColor: Colors.white70,
      backgroundColor: Colors.black87,
      listener: AdropPopupListener(
        onAdReceived: (ad) {
          debugPrint('ポップアップ広告読み込み完了');
          setState(() => isLoaded = true);
        },
        onAdDidDismissFullScreen: (ad) {
          debugPrint('ポップアップ広告閉じる');
          _createPopupAd();
        },
        onAdFailedToReceive: (ad, errorCode) {
          debugPrint('ポップアップ広告読み込み失敗: $errorCode');
          if (errorCode == AdropErrorCode.adHideForToday) {
            debugPrint('ユーザーが今日は表示しないを選択しました。');
          }
        },
      ),
    );

    setState(() => isLoaded = false);
  }

  @override
  void dispose() {
    popupAd?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('ポップアップ広告')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => popupAd?.load(),
              child: const Text('広告を読み込む'),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: isLoaded ? () => popupAd?.show() : null,
              child: const Text('広告を表示'),
            ),
          ],
        ),
      ),
    );
  }
}

高度な例

ダークモード対応

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initializeAdrop();
  }

  Future<void> _initializeAdrop() async {
    await Adrop.initialize(true);

    // システムテーマに自動追従
    await Adrop.setTheme(AdropTheme.auto);
  }

  @override
  void didChangePlatformBrightness() {
    // システムテーマ変更検出時の処理
    // AdropTheme.auto使用時は自動処理されます
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      themeMode: ThemeMode.system,
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      home: const HomeScreen(),
    );
  }
}

ユーザーターゲティング設定

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

class UserProfileScreen extends StatelessWidget {
  final User user;

  const UserProfileScreen({super.key, required this.user});

  Future<void> _setupTargeting() async {
    // UID設定
    await Adrop.setUID(user.id);

    // 基本プロパティ設定
    await AdropMetrics.setProperty('birth', user.birthDate);
    await AdropMetrics.setProperty('gender', user.gender);

    // カスタムプロパティ設定
    await AdropMetrics.setProperty('membership_level', user.membershipLevel);
    await AdropMetrics.setProperty('total_purchase', user.totalPurchase);
    await AdropMetrics.setProperty('is_premium', user.isPremium);

    // イベントログ
    await AdropMetrics.logEvent('profile_view', {
      'user_id': user.id,
      'membership': user.membershipLevel,
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('プロフィール')),
      body: Center(
        child: ElevatedButton(
          onPressed: _setupTargeting,
          child: const Text('ターゲティング設定'),
        ),
      ),
    );
  }
}

class User {
  final String id;
  final String birthDate;
  final String gender;
  final String membershipLevel;
  final int totalPurchase;
  final bool isPremium;

  User({
    required this.id,
    required this.birthDate,
    required this.gender,
    required this.membershipLevel,
    required this.totalPurchase,
    required this.isPremium,
  });
}

広告の事前読み込み

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

class AdPreloader {
  static AdropInterstitialAd? _interstitialAd;
  static AdropRewardedAd? _rewardedAd;
  static bool _isInterstitialReady = false;
  static bool _isRewardedReady = false;

  static void preloadInterstitial() {
    _interstitialAd?.dispose();
    _interstitialAd = AdropInterstitialAd(
      unitId: 'YOUR_INTERSTITIAL_UNIT_ID',
      listener: AdropInterstitialListener(
        onAdReceived: (ad) {
          _isInterstitialReady = true;
          debugPrint('インタースティシャル広告準備完了');
        },
        onAdDidDismissFullScreen: (ad) {
          _isInterstitialReady = false;
          // 次のために再読み込み
          Future.delayed(const Duration(seconds: 1), preloadInterstitial);
        },
        onAdFailedToReceive: (ad, errorCode) {
          _isInterstitialReady = false;
          // 再試行
          Future.delayed(const Duration(seconds: 5), preloadInterstitial);
        },
      ),
    );
    _interstitialAd?.load();
  }

  static void preloadRewarded() {
    _rewardedAd?.dispose();
    _rewardedAd = AdropRewardedAd(
      unitId: 'YOUR_REWARDED_UNIT_ID',
      listener: AdropRewardedListener(
        onAdReceived: (ad) {
          _isRewardedReady = true;
          debugPrint('リワード広告準備完了');
        },
        onAdDidDismissFullScreen: (ad) {
          _isRewardedReady = false;
          Future.delayed(const Duration(seconds: 1), preloadRewarded);
        },
        onAdFailedToReceive: (ad, errorCode) {
          _isRewardedReady = false;
          Future.delayed(const Duration(seconds: 5), preloadRewarded);
        },
      ),
    );
    _rewardedAd?.load();
  }

  static bool get isInterstitialReady => _isInterstitialReady;
  static bool get isRewardedReady => _isRewardedReady;

  static void showInterstitial() {
    if (_isInterstitialReady) {
      _interstitialAd?.show();
      _isInterstitialReady = false;
    }
  }

  static void showRewarded(
      void Function(int type, int amount)? onEarnReward) {
    if (_isRewardedReady) {
      if (onEarnReward != null) {
        _rewardedAd = AdropRewardedAd(
          unitId: 'YOUR_REWARDED_UNIT_ID',
          listener: AdropRewardedListener(
            onAdEarnRewardHandler: (ad, type, amount) {
              onEarnReward(type, amount);
            },
            onAdDidDismissFullScreen: (ad) {
              _isRewardedReady = false;
              preloadRewarded();
            },
          ),
        );
      }
      _rewardedAd?.show();
      _isRewardedReady = false;
    }
  }

  static void dispose() {
    _interstitialAd?.dispose();
    _rewardedAd?.dispose();
    _interstitialAd = null;
    _rewardedAd = null;
    _isInterstitialReady = false;
    _isRewardedReady = false;
  }
}

// アプリ起動時に呼び出し
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Adrop.initialize(true);

  // 広告を事前読み込み
  AdPreloader.preloadInterstitial();
  AdPreloader.preloadRewarded();

  runApp(const MyApp());
}

関連ドキュメント