Integrating with Ad Networks in Flutter

Mobile app monetization is crucial for developers, and integrating ad networks is a common strategy. Flutter, with its cross-platform capabilities, simplifies this process. This post will guide you through integrating ad networks, such as AdMob and Facebook Audience Network, into your Flutter applications.

Why Integrate Ad Networks in Flutter?

  • Monetization: Generate revenue from your app by displaying ads to users.
  • Cross-Platform Reach: Implement ads across iOS and Android with a single codebase.
  • User Experience: Balance ad frequency and placement to maintain a positive user experience.

Overview of Popular Ad Networks

  • AdMob (Google): One of the most popular ad networks, offering various ad formats.
  • Facebook Audience Network: Allows you to monetize your app with Facebook ads.
  • Unity Ads: Popular for gaming apps, providing video ads and rewarded ads.

Integrating AdMob in Flutter

Step 1: Set Up AdMob Account and Create Ad Units

Before integrating AdMob into your Flutter app, you need to set up an AdMob account and create ad units (banner, interstitial, rewarded).

Step 2: Add the google_mobile_ads Package

Add the google_mobile_ads package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  google_mobile_ads: ^4.0.0

Then, run flutter pub get to install the package.

Step 3: Initialize the Mobile Ads SDK

Initialize the Mobile Ads SDK in your main.dart file:

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();
  runApp(MyApp());
}

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AdMob Example'),
      ),
      body: Center(
        child: Text('Ad Content Here'),
      ),
    );
  }
}

Step 4: Implement Banner Ads

Here’s how to implement banner ads:

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io' show Platform;

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

class _MyHomePageState extends State {
  BannerAd? _bannerAd;
  bool _isBannerAdReady = false;

  // Use your own Ad Unit ID from AdMob
  final String bannerAdUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/6300978111' // Test banner ad unit ID (Android)
      : 'ca-app-pub-3940256099942544/2934735716'; // Test banner ad unit ID (iOS)

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

  void _loadBannerAd() {
    _bannerAd = BannerAd(
      adUnitId: bannerAdUnitId,
      request: AdRequest(),
      size: AdSize.banner,
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) {
          print('$ad loaded.');
          setState(() {
            _isBannerAdReady = true;
          });
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('Banner ad failed to load: ${error.message}');
          setState(() {
            _isBannerAdReady = false;
          });
          ad.dispose();
        },
        onAdOpened: (Ad ad) => print('$ad opened.'),
        onAdClosed: (Ad ad) => print('$ad closed.'),
      ),
    );
    _bannerAd!.load();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AdMob Example'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Center(
              child: Text('Ad Content Here'),
            ),
          ),
          if (_isBannerAdReady)
            Container(
              alignment: Alignment.center,
              width: _bannerAd!.size.width.toDouble(),
              height: _bannerAd!.size.height.toDouble(),
              child: AdWidget(ad: _bannerAd!),
            ),
        ],
      ),
    );
  }
}

Step 5: Implement Interstitial Ads

Interstitial ads are full-screen ads that cover the app’s interface. Here’s how to implement them:

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io' show Platform;

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

class _MyHomePageState extends State {
  InterstitialAd? _interstitialAd;
  bool _isInterstitialAdReady = false;

  // Use your own Ad Unit ID from AdMob
  final String interstitialAdUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/1033173712' // Test interstitial ad unit ID (Android)
      : 'ca-app-pub-3940256099942544/4411468910'; // Test interstitial ad unit ID (iOS)

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

  void _loadInterstitialAd() {
    InterstitialAd.load(
      adUnitId: interstitialAdUnitId,
      request: AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (InterstitialAd ad) {
          this._interstitialAd = ad;
          ad.fullScreenContentCallback = FullScreenContentCallback(
            onAdDismissedFullScreenContent: (InterstitialAd ad) {
              setState(() {
                _isInterstitialAdReady = false;
              });
              _loadInterstitialAd();
            },
            onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
              print('Ad failed to show: ${error.message}');
              setState(() {
                _isInterstitialAdReady = false;
              });
              ad.dispose();
              _loadInterstitialAd();
            },
          );
          setState(() {
            _isInterstitialAdReady = true;
          });
        },
        onAdFailedToLoad: (LoadAdError error) {
          print('Interstitial ad failed to load: ${error.message}');
          setState(() {
            _isInterstitialAdReady = false;
          });
        },
      ),
    );
  }

  void _showInterstitialAd() {
    if (_isInterstitialAdReady) {
      _interstitialAd?.show();
    } else {
      print('Interstitial ad is not ready yet.');
    }
  }

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

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

Step 6: Implement Rewarded Ads

Rewarded ads provide users with incentives for watching ads, such as in-app currency or bonus items. Here’s the code:

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io' show Platform;

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

class _MyHomePageState extends State {
  RewardedAd? _rewardedAd;
  bool _isRewardedAdReady = false;
  int _rewardAmount = 0;

  // Use your own Ad Unit ID from AdMob
  final String rewardedAdUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/5224354917' // Test rewarded ad unit ID (Android)
      : 'ca-app-pub-3940256099942544/1712485313'; // Test rewarded ad unit ID (iOS)

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

  void _loadRewardedAd() {
    RewardedAd.load(
      adUnitId: rewardedAdUnitId,
      request: AdRequest(),
      rewardedAdLoadCallback: RewardedAdLoadCallback(
        onAdLoaded: (RewardedAd ad) {
          this._rewardedAd = ad;
          ad.fullScreenContentCallback = FullScreenContentCallback(
            onAdDismissedFullScreenContent: (RewardedAd ad) {
              setState(() {
                _isRewardedAdReady = false;
              });
              _loadRewardedAd();
            },
            onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
              print('Ad failed to show: ${error.message}');
              setState(() {
                _isRewardedAdReady = false;
              });
              ad.dispose();
              _loadRewardedAd();
            },
          );
          setState(() {
            _isRewardedAdReady = true;
          });
        },
        onAdFailedToLoad: (LoadAdError error) {
          print('Rewarded ad failed to load: ${error.message}');
          setState(() {
            _isRewardedAdReady = false;
          });
        },
      ),
    );
  }

  void _showRewardedAd() {
    if (_isRewardedAdReady) {
      _rewardedAd!.show(
        onUserEarnedReward: (Ad ad, RewardItem reward) {
          setState(() {
            _rewardAmount += reward.amount.toInt();
          });
          print('User earned reward: ${reward.amount} ${reward.type}');
        },
      );
    } else {
      print('Rewarded ad is not ready yet.');
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AdMob Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Reward Amount: $_rewardAmount'),
            ElevatedButton(
              onPressed: _showRewardedAd,
              child: Text('Show Rewarded Ad'),
            ),
          ],
        ),
      ),
    );
  }
}

Integrating Facebook Audience Network in Flutter

Step 1: Set Up Facebook Developer Account and Create Ad Placements

Set up a Facebook Developer account and create ad placements (banner, interstitial, rewarded) on the Facebook Audience Network platform.

Step 2: Add the flutter_facebook_audience_network Package

Include the flutter_facebook_audience_network package in your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_facebook_audience_network: ^1.0.0

Run flutter pub get to install the package.

Step 3: Initialize the Facebook Audience Network SDK

Initialize the Facebook Audience Network SDK in your main.dart:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FacebookAudienceNetwork.init();
  runApp(MyApp());
}

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Facebook Audience Network Example'),
      ),
      body: Center(
        child: Text('Ad Content Here'),
      ),
    );
  }
}

Step 4: Implement Banner Ads

Here’s how to display banner ads:

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

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

class _MyHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Facebook Audience Network Example'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Center(
              child: Text('Ad Content Here'),
            ),
          ),
          FacebookBannerAd(
            placementId: "YOUR_PLACEMENT_ID", // Replace with your placement ID
            bannerSize: BannerSize.STANDARD,
            listener: (result, value) {
              print("Banner Ad: $result -->  $value");
            },
          ),
        ],
      ),
    );
  }
}

Step 5: Implement Interstitial Ads

Display full-screen interstitial ads as follows:

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

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

class _MyHomePageState extends State {
  @override
  void initState() {
    super.initState();
    _loadInterstitialAd();
  }

  void _loadInterstitialAd() {
    FacebookInterstitialAd.loadInterstitialAd(
      placementId: "YOUR_PLACEMENT_ID", // Replace with your placement ID
      listener: (result, value) {
        print("Interstitial Ad: $result --> $value");
        if (result == InterstitialAdResult.LOADED) {
          FacebookInterstitialAd.showInterstitialAd();
        }
      },
    );
  }

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

Step 6: Implement Rewarded Video Ads

Display rewarded video ads and provide incentives:

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

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

class _MyHomePageState extends State {
  int _rewardAmount = 0;

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

  void _loadRewardedAd() {
    FacebookRewardedVideoAd.loadRewardedVideoAd(
      placementId: "YOUR_PLACEMENT_ID", // Replace with your placement ID
      listener: (result, value) {
        print("Rewarded Ad: $result --> $value");
        if (result == RewardedVideoAdResult.LOADED) {
          FacebookRewardedVideoAd.showRewardedVideoAd();
        }
        if (result == RewardedVideoAdResult.VIDEO_COMPLETE) {
          setState(() {
            _rewardAmount += 10; // Example: Reward the user 10 points
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Facebook Audience Network Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Reward Amount: $_rewardAmount'),
            ElevatedButton(
              onPressed: _loadRewardedAd,
              child: Text('Show Rewarded Video Ad'),
            ),
          ],
        ),
      ),
    );
  }
}

Tips for Optimizing Ad Integrations

  • Ad Placement: Strategically place ads where they are least intrusive.
  • Frequency: Avoid bombarding users with too many ads.
  • A/B Testing: Experiment with different ad formats and placements to optimize performance.
  • User Feedback: Monitor user reviews and feedback to fine-tune ad strategies.

Conclusion

Integrating ad networks into your Flutter apps allows you to generate revenue effectively. By implementing AdMob or Facebook Audience Network, and optimizing ad placements and frequency, you can achieve a balance between monetization and user experience. These techniques ensure that your app remains both profitable and enjoyable for users.