customadswidget 1.1.0
customadswidget: ^1.1.0 copied to clipboard
Non-intrusive custom ads for Flutter Web: image banners and templates loaded from a remote JSON, rotation, scheduling and viewable impression tracking.
Custom Ads Widget #
A Flutter package for building and displaying non-intrusive custom ads on the web. It renders your own banners or template-based ads, loads them from a remote JSON, and tracks impressions and clicks.
Overview #
This package handles the ad side of a Flutter Web app, so you don't have to build it from scratch. Your client (or your own backend) publishes a JSON file with banners, images, links and schedules. You drop an AdSlot wherever an ad should appear, and the package takes care of the rest:
- choosing the right image for the screen size;
- rotating ads;
- respecting start and end dates;
- opening the link when the user clicks;
- reporting viewable impressions.
Every ad follows a built-in non-intrusive policy based on the Better Ads Standards and the Acceptable Ads criteria:
- each ad is always labeled;
- its size is capped;
- animations are frozen;
- rotation is slow.
There are no pop-ups, interstitials, sticky ads, video or sound.
Features #
This package includes the following widgets and classes.
AdSlot #
The main widget. It shows the ads for one placement (a named spot on the page, such as home_top or sidebar) defined in the remote JSON.
- Reads from the
AdSourceprovided byCustomAdScope, or from one passed directly. - Shows a single ad, or rotates them automatically when the placement has several.
- Skips ads outside their
startAt/endAtdates. - Renders nothing (or an optional
placeholder) when the placement doesn't exist, has no active ads, or the JSON fails to load, so empty slots never leave a gap. - Accepts a
builderto draw remote ads with your own design.
CustomAd #
A single ad, built from an AdData and shown in any AdFormat.
- Formats:
banner: 320x50 standard banner (great for bottom bars and mobile navigation);largeBanner: 320x100 large banner;fullBanner: 468x60 tablet/desktop banner;leaderboard: 728x90;mediumRectangle: 300x250;skyscraper: 160x600;card: fluid width;hero: full width;custom: custom-sized ad;creative: your own image, as designed.
- Customizable size: pass
size: Size(width, height)(e.g.Size(double.infinity, 50)for full-width bottom banners) or use the convenientCustomAd.banner(...)constructor. - Hover effects for the web: click cursor, elevation and a slight scale.
- Clicks: a click opens
targetUrl, in a new tab by default. - Viewable impressions: an impression counts when at least 50% of the ad stays visible for 1 second (the IAB criterion), once per mounted ad.
- Optional close button (
dismissible). - Fully custom content through
builder, while keeping clicks, tracking, sizing and policy enforcement.
CustomAdRotator #
Rotates a list of ads in the same space.
- Fades between ads at a fixed interval, with a minimum of 30 seconds.
- Pauses while the mouse is over it, so the ad doesn't change right before a click.
- Closing any ad hides the whole rotator.
CustomAdScope #
Shared configuration for every ad below it. Place it once at the top of your app.
source: theAdSourcethat everyAdSlotreads from.style: the defaultAdStylefor template ads.policy: the thresholds of the non-intrusive policy.onImpression/onClick: one place to connect your analytics.onOpenUrl: how a click opens the ad's link. It defaults tourl_launcher; replace it to route clicks inside your app or to test without a browser.CustomAdScope.merge(...)overrides some values for one section of the page and inherits the rest.
AdSource #
Where AdSlot gets its ads from. Every source shares the same behavior:
- One instance is shared by every
AdSlot, and simultaneous requests are merged into one. - Optional
refreshIntervalto pick up new banners without reloading the page. - If a reload fails, it keeps showing the last valid configuration.
- Exposes
config,error,isLoading,ensureLoaded()andreload().
The package includes three sources:
RemoteAdSource(url)downloads the JSON from a URL. Relative image and link URLs are resolved against it, and optionalheaderscan carry an API key.AssetAdSource(path)reads the JSON from the app's assets, with no server.MemoryAdSource(config)holds ads that are already in memory, for example fetched by your own API client. Callupdate(config)to replace them.
To read ads from anywhere else (Firebase, a database...), extend AdSource and implement fetchConfig():
class FirestoreAdSource extends AdSource {
@override
Future<AdConfig> fetchConfig() async {
final doc = await FirebaseFirestore.instance.doc('config/ads').get();
return AdConfig.fromJson(doc.data()!);
}
}
AdData and AdAsset #
The content of an ad, independent of how it is drawn.
- Text fields for template ads:
title,description,ctaLabelandsponsor. assets: one image per size forcreativebanners. The widest one that fits is used.- Click destination (
targetUrl), label (badge) and schedule (startAt/endAt). AdData.fromJson/toJsonfor loading ads from any API.
AdStyle #
Controls the look of template ads. Values you don't set come from your app's ColorScheme, so ads also adapt to dark mode.
- Background color or gradient, text and accent colors, border, corner radius, elevation and hover scale.
- Ready-made styles:
AdStyle.dark(): dark background;AdStyle.vibrant(color): gradient based on one color;AdStyle.creative: no rounded corners or zoom, the default for image banners.
copyWithto adjust any of them.resolve(context)returns aResolvedAdStyle, whose colors are never null. That's the typebuildercallbacks receive.
AdPolicy #
The non-intrusive rules. They are always on. You can change the thresholds, but not turn the rules off.
- Every ad shows a label:
badge, or the policylabelwhen the ad has none. - Landscape and rectangular ads are scaled down if taller than 30% of the screen.
- Vertical ads count as side ads. They only show on screens at least 1024px wide, and at most 350px wide.
- Animated GIF, WebP and PNG images are frozen on their first frame.
- Rotation is never faster than every 30 seconds.
Building blocks #
AdImage, AdCta and AdMetaLine are the parts the built-in layouts use. Use them in your own builder designs. AdImage also freezes animations, so prefer it over Image.network.
Supported Formats #
| Format | Size | Behavior |
|---|---|---|
banner |
320x50 | Standard mobile/bottom banner. Compact layout. |
largeBanner |
320x100 | Large mobile banner with room for description. |
fullBanner |
468x60 | Full horizontal banner for tablets and desktop. |
leaderboard |
728x90 | Switches to a 320x50 mobile banner below 728px of width. |
mediumRectangle |
300x250 | Default format. Image on top, text and button below. |
skyscraper |
160x600 | Vertical side ad, shown on desktop only (see AdPolicy). |
card |
Fluid width | 16:9 image plus text. Ideal for feeds and grids. |
hero |
Full width | Image as background with a dark overlay and large text. |
custom |
Fluid / Custom | Layout adapts to custom dimensions provided via size. |
creative |
Taken from image (assets) |
Shows the advertiser's own banner as-is. Picks the widest asset that fits. |
Fixed sizes follow the IAB standard units. They shrink when the container is narrower, and never stretch. You can also override the size of any format by passing size: Size(width, height) (e.g. Size(double.infinity, 50) for full-width bottom banners).
Properties per Widget #
| Widget | Properties |
|---|---|
AdSlot |
placement: (required) placement ID from the JSON.source: AdSource to read from (defaults to the one in CustomAdScope).size: custom Size override for ads in this slot.style: AdStyle for template ads.builder: custom design for this slot's ads.placeholder: widget shown when there is nothing to display. |
CustomAd |
ad: (required) the AdData to show.format: AdFormat (default mediumRectangle).size: custom Size (e.g. Size(double.infinity, 50) for bottom banners).style: AdStyle (defaults to the scope's, or AdStyle.creative for creative).builder: (context, ad, style, hovered) => Widget for fully custom content.onTap, onImpression, onClose: per-ad callbacks.dismissible: shows a close button (default false).openInNewTab: opens targetUrl in a new tab (default true). |
CustomAdRotator |
ads: (required) non-empty list of AdData.interval: time between ads (default and minimum: 30 s).format, size, style, builder, dismissible, onTap, onImpression: same as CustomAd. |
CustomAdScope |
child: (required) the subtree.source: AdSource for every AdSlot.style: default AdStyle.policy: AdPolicy thresholds (default AdPolicy.nonIntrusive).onImpression, onClick: global analytics callbacks.onOpenUrl: (uri, {required newTab}) async {...} to open links (default CustomAdScope.defaultOpenUrl). |
RemoteAdSource |
url: (required) URL of the ads JSON.refreshInterval: reload the JSON periodically.headers: extra request headers.client: custom http.Client (handy for tests). |
AssetAdSource |
path: (required) asset path of the JSON.bundle: AssetBundle to read from (defaults to rootBundle). |
MemoryAdSource |
config: (required) the initial AdConfig. update(config) replaces it. |
AdData |
id: (required) used for tracking.title: (required) visible title, or alt text for creative.description, imageUrl, sponsor: template content.ctaLabel: button text (default 'Learn more').assets: list of AdAsset(url, width, height) for creative.targetUrl: click destination.badge: label text (default 'Ad').startAt, endAt: schedule. |
AdStyle |
backgroundColor, gradient, foregroundColor, accentColor, onAccentColor, border, titleStyle, descriptionStyle.borderRadius: default 12.elevation: default 1.hoverElevation: default 6.hoverScale: default 1.015. |
AdPolicy |
label: label for ads without a badge (default 'Ad').maxViewportHeightFraction: maximum ad height relative to the screen (default 0.3).minViewportWidthForVerticalAds: default 1024.maxVerticalAdWidth: default 350.minRotationInterval: default 30 s. |
Remote JSON #
The client publishes one JSON file over HTTPS. Each key in placements matches an AdSlot(placement: ...) in the app:
{
"version": 1,
"placements": {
"home_top": {
"rotationSeconds": 30,
"ads": [
{
"id": "summer-2026",
"alt": "Summer sale: 50% off",
"targetUrl": "https://example.com/summer",
"endAt": "2027-01-31T23:59:59-03:00",
"assets": [
{ "url": "banners/summer-728x90.png", "width": 728, "height": 90 },
{ "url": "banners/summer-320x50.png", "width": 320, "height": 50 }
]
}
]
},
"blog_card": {
"format": "card",
"ads": [
{
"id": "coffee",
"title": "Specialty coffee at your door",
"description": "Freshly roasted beans every week.",
"imageUrl": "banners/coffee.jpg",
"ctaLabel": "Subscribe",
"targetUrl": "https://example.com/coffee"
}
]
},
"bottom_bar": {
"format": "banner",
"width": 320,
"height": 50,
"ads": [
{
"id": "flash-deal",
"title": "Flash deal: 20% off today",
"ctaLabel": "Shop now",
"targetUrl": "https://example.com/deals"
}
]
}
}
}
Server requirements:
- HTTPS.
Content-Type: application/json; charset=utf-8.Access-Control-Allow-Origin(CORS) on both the JSON and the images. Images are decoded by Flutter so that animations can be frozen, and the browser only allows that with CORS.
The full field reference, image guidelines and CORS examples for Nginx, Apache, Express, S3, Netlify and Firebase are in doc/server-setup.md.
Screenshots #
Sample creative banners included with the example app:

Getting Started #
To use this package, add customadswidget as a dependency in your pubspec.yaml file:
dependencies:
customadswidget: ^1.1.0
Or run this command in your terminal:
flutter pub add customadswidget
Then, import the package in your Dart code:
import 'package:customadswidget/customadswidget.dart';
Usage #
Create one RemoteAdSource, provide it with a CustomAdScope, and place an AdSlot wherever an ad should appear:
import 'package:flutter/material.dart';
import 'package:customadswidget/customadswidget.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _ads = RemoteAdSource(
Uri.parse('https://cdn.example.com/ads/ads.json'),
refreshInterval: const Duration(minutes: 5),
);
@override
void dispose() {
_ads.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
// One scope for the whole app: ads source, policy and analytics.
builder: (context, child) => CustomAdScope(
source: _ads,
policy: const AdPolicy(label: 'Sponsored'),
onImpression: (ad) => debugPrint('impression: ${ad.id}'),
onClick: (ad) => debugPrint('click: ${ad.id}'),
child: child!,
),
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Custom Ads Example')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
// Remote banners: the JSON decides what goes in each placement.
const Center(child: AdSlot(placement: 'home_top')),
const SizedBox(height: 24),
// Remote ads with an optional placeholder.
const AdSlot(
placement: 'blog_card',
placeholder: Text('No ads right now'),
),
const SizedBox(height: 24),
// A template ad defined in code.
CustomAd(
ad: const AdData(
id: 'coffee',
title: 'Specialty coffee at your door',
description: 'Freshly roasted beans every week.',
imageUrl: 'https://example.com/coffee.jpg',
ctaLabel: 'Subscribe',
targetUrl: 'https://example.com/coffee',
sponsor: 'South Roasters',
),
format: AdFormat.card,
style: AdStyle.vibrant(Colors.deepOrange),
dismissible: true,
),
const SizedBox(height: 24),
// Standard or bottom banner with customizable size (e.g. full-width bottom bar):
CustomAd.banner(
ad: const AdData(
id: 'deal-bottom',
title: 'Get 20% off today',
ctaLabel: 'Claim',
targetUrl: 'https://example.com/deal',
),
size: const Size(double.infinity, 50),
),
const SizedBox(height: 24),
// Your own banner image, one asset per size.
const CustomAd(
format: AdFormat.creative,
ad: AdData(
id: 'summer',
title: 'Summer sale: 50% off', // used as alt text
targetUrl: 'https://example.com/summer',
assets: [
AdAsset(url: 'https://example.com/summer-728x90.png', width: 728, height: 90),
AdAsset(url: 'https://example.com/summer-320x50.png', width: 320, height: 50),
],
),
),
const SizedBox(height: 24),
// Several ads rotating in the same space.
const CustomAdRotator(
format: AdFormat.leaderboard,
ads: [
AdData(id: 'a', title: 'First offer', ctaLabel: 'See more'),
AdData(id: 'b', title: 'Second offer', ctaLabel: 'See more'),
],
),
const SizedBox(height: 24),
// Fully custom design: clicks, tracking and policy still apply.
CustomAd(
ad: const AdData(id: 'custom', title: 'Built with builder'),
builder: (context, ad, style, hovered) => Center(
child: Text(
ad.title,
style: TextStyle(fontSize: hovered ? 24 : 20),
),
),
),
],
),
);
}
}
Bottom Banners & Custom Dimensions #
To display a banner at the bottom of the screen (docked or in a bottom navigation bar), you can place it inside Scaffold.bottomNavigationBar:
// Full-width bottom banner (fills available width at 50px height)
Scaffold(
body: const HomePageContent(),
bottomNavigationBar: SafeArea(
child: CustomAd.banner(
ad: const AdData(
id: 'deal-bottom',
title: 'Special weekend offer: 20% off',
ctaLabel: 'Claim',
targetUrl: 'https://example.com/deal',
),
size: const Size(double.infinity, 50),
),
),
);
// Standard centered banner (320x50 default size)
Scaffold(
body: const HomePageContent(),
bottomNavigationBar: SafeArea(
child: CustomAd.banner(ad: myAd),
),
);
// Remote bottom slot with custom size
Scaffold(
body: const HomePageContent(),
bottomNavigationBar: const SafeArea(
child: AdSlot(
placement: 'bottom_bar',
size: Size(double.infinity, 50),
),
),
);
Loading ads without a server #
Banners can also ship inside the app as Flutter assets. Use AssetAdSource with the same JSON format; image paths starting with assets/ are loaded as Flutter assets:
CustomAdScope(
source: AssetAdSource('assets/ads/local_ads.json'),
child: MyApp(),
)
// Anywhere in the app
const AdSlot(placement: 'offline')
Opening links inside the app #
By default a click opens targetUrl with url_launcher. To handle it yourself, for example to route internal links with your router:
CustomAdScope(
onOpenUrl: (uri, {required newTab}) async {
if (uri.host == 'myapp.com') {
router.go(uri.path);
} else {
await CustomAdScope.defaultOpenUrl(uri, newTab: newTab);
}
},
child: MyApp(),
)
Example App #
example/ is a web app that shows every feature, each one with its code. It has a page for each of these topics:
- remote banners;
- the non-intrusive policy;
- formats;
- styles;
- behavior;
- custom design;
- local JSON;
- an editor that generates the server JSON;
- an analytics event log.
cd example
flutter run -d chrome
Tests #
flutter test # package
cd example && flutter test # example app
Additional Information #
To report an issue or contribute, please open an issue or a pull request in the GitHub repository. Feedback and contributions are welcome!
License #
MIT. See LICENSE.