native_admob_flutter 0.0.6+4 copy "native_admob_flutter: ^0.0.6+4" to clipboard
native_admob_flutter: ^0.0.6+4 copied to clipboard

discontinuedreplaced by: google_mobile_ads
outdated

Create native ads easily purely in dart using PlatformViews and Google's ADMOB Sdk

native_admob_flutter #

Easy-to-make native ads in flutter with Google's AdMob SDK.

English | Português

Read the wiki for advanced usage and more info

Platform setup #

Desktop (Windows, macOS and Linux) and Web are out of reach

Android #

Add your ADMOB App ID (How to find it?) in AndroidManifest.xml.

<manifest>
  <application>
    <!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
    <meta-data
      android:name="com.google.android.gms.ads.APPLICATION_ID"
      android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy">
  </application>
</manifest>

Change minSdkVersion to 19. It's the minimum sdk version required by flutter to use a PlatformView. Learn more

android {
    defaultConfig {
        minSdkVersion 19
    }
}

Enabling hybrid composition #

Once initialized, you can enable hybrid composition as following:

NativeAds.useHybridComposition = true;

Or you can enable it on initialization:

NativeAds.initialize(useHybridComposition: true);

It's enabled by default on Android 19. Note that on Android versions prior to Android 10 Hybrid Composition has some performance drawbacks.

Note: It autommatically does the checking for you about the android version, so you don't need to worry about it.

iOS #

iOS is currently not supported (I don't have an Apple environment :/). Feel free to create a pull request with the implementation for it :)

Web #

Web is currently not supported.

Initialize #

Before creating any native ads, you must initalize the admob. It can be initialized only once:

import 'package:flutter/foundation.dart';

String get admobUnitId {
  /// Always test with test ads
  if (kDebugMode)
    return NativeAds.testAdUnitId;
  else return 'your-native-ad-unit-id';
}

void main() async {
  // Add this line if you will initialize it before runApp
  WidgetsFlutterBinding.ensureInitialized();
  // default native ad unit id: ca-app-pub-3940256099942544/2247696110
  /* await */ NativeAds.initialize(nativeAdUnitId: admobUnitId);
  runApp(MyApp());
}

❗NOTE:❗ Unit IDs are NOT App IDs

Always test with test ads #

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use the dedicated test ad unit ID for Native Ads on Android:

App ID: ca-app-pub-3940256099942544~3347511713
Unit ID: ca-app-pub-3940256099942544/2247696110

It's been specially configured to return test ads for every request, and you're free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK's test ads work, see Test Ads.

Learn how to create your own native ads unit ids here

When to request ads #

Applications displaying native ads are free to request them in advance of when they'll actually be displayed. In many cases, this is the recommended practice. An app displaying a list of items with native ads mixed in, for example, can load native ads for the whole list, knowing that some will be shown only after the user scrolls the view and some may not be displayed at all.

Creating an ad #

To create an ad, use the widget NativeAd:

NativeAd(
  buildLayout: adBannerLayoutBuilder,
  loading: Text('loading'),
  error: Text('error'),
)

This library provides a default layout builder: adBannerLayoutBuilder: A native ad screenshot

Creating a layout builder #

You can use each provided view only once. headline and attribution are required to be in the view by google

// ⭐Note⭐: The function must be a getter, otherwise hot reload will not work
AdLayoutBuilder get myCustomLayoutBuilder => (ratingBar, media, icon, headline,
    advertiser, body, price, store, attribution, button) {
  return AdLinearLayout(
    margin: EdgeInsets.all(10),
    borderRadius: AdBorderRadius.all(10),
    // The first linear layout width needs to be extended to the
    // parents width, otherwise the children won't fit good
    width: MATCH_PARENT,
    children: [
      AdLinearLayout(
        children: [
          icon,
          AdLinearLayout(
            children: [
              headline,
              AdLinearLayout(
                children: [attribution, advertiser],
                orientation: HORIZONTAL,
                width: WRAP_CONTENT,
              ),
            ],
          ),
        ],
        width: WRAP_CONTENT,
        orientation: HORIZONTAL,
        margin: EdgeInsets.all(6),
      ),
      button,
    ],
    backgroundColor: Colors.blue,
  );
};

🔴IMPORTANT❗🔴: You can NOT use flutter widgets to build your layouts

To use it in your NativeAd, pass it as an argument to layoutBuilder:

NativeAd(
  layoutBuilder: myCustomLayoutBuilder
)

Your layout must follow google's native ads policy & guidelines. Learn more:

Customizing views #

All the avaiable views are customizable. To customize a view use:

NativeAd(
  layoutBuilder: ...,
  headling: AdTextView(
    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.black),
    maxLines: 1,
  ),
  attribution: AdTextView(
    width: WRAP_CONTENT, // You can use WRAP_CONTENT
    height: WRAP_CONTENT, // or MATCH_PARENT
    padding: EdgeInsets.symmetric(horizontal: 2, vertical: 1),
    backgroundColor: Colors.yellow,
    // The label to indicate the ad is an ad.
    // You can change it depending on the device's language
    text: 'Ad',
    margin: EdgeInsets.only(right: 2),
    maxLines: 1,
    borderRadius: AdBorderRadius.all(10),
  ),
  button: AdButtonView(
    backgroundColor: Colors.yellow,
    margin: EdgeInsets.all(6),
    borderRadius: AdBorderRadius.vertical(bottom: 10),
  ),
)

Avaiable views #

Field Class Description Always included? Required to be displayed?
Headline AdTextView Primary headline text (e.g., app title or article title). Yes Yes
Attribution AdTextView Indicate that the ad is an ad Yes Yes
Image AdMediaView Large, primary image. Yes Recommended
Body AdTextView Secondary body text (e.g., app description or article description). Yes Recommended
Icon AdImageView Small icon image (e.g., app store image or advertiser logo). No Recommended
Call to action AdButtonView Button or text field that encourages user to take action. No Recommended
Star rating AdRatingBarView Rating from 0-5 that represents the average rating of the app in a store. No Recommended
Store AdTextView The app store where the user downloads the app. No Recommended
Price AdTextView Cost of the app. No Recommended
Advertiser AdTextView Text that identifies the advertiser (e.g., advertiser or brand name). No Recommended

Learn more

More screenshots

The code for these can be found in example

Using controller and listening to events #

// Init the controller
final controller = NativeAdController();

@override
void initState() {
  super.initState();
  controller.onEvent.listen((e) {
      final event = e.keys.first;
      switch (event) {
        case AdEvent.loading:
          print('loading');
          break;
        case AdEvent.loaded:
          print('loaded');
          break;
        case AdEvent.loadFailed:
          final errorCode = e.values.first;
          print('loadFailed $errorCode');
          break;
        case AdEvent.impression:
          print('ad rendered');
          break;
        case AdEvent.clicked;
          print('clicked');
          break;
        case AdEvent.muted:
          showDialog(
            ...,
            builder: (_) => AlertDialog(title: Text('Ad muted')),
          );
          break;
        default:
          break;
      }
  });
}

// Use the controller in the NativeAd
@override
Widget build(BuildContext context) {
  return NativeAd(controller: controller);
}

// Dispose the controller.
// You can't use the it again once it's disposed
@override
void dispose() {
  controller.dispose();
  super.dispose();
}

TODO: #

141
likes
0
pub points
73%
popularity

Publisher

verified publisherbdlukaa.dev

Create native ads easily purely in dart using PlatformViews and Google's ADMOB Sdk

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

Dependencies

flutter

More

Packages that depend on native_admob_flutter