smartlinks_ad 1.7.0 copy "smartlinks_ad: ^1.7.0" to clipboard
smartlinks_ad: ^1.7.0 copied to clipboard

A Flutter package for Linklytics SmartLinks Ads.

smartlinks_ad #

A Flutter package for integrating Linklytics SmartLinks Ads into your mobile applications. This package provides easy-to-use widgets for displaying Banner, Interstitial, and Native ads powered by the Linklytics ad network.

Features #

  • Banner Ads: Configurable banner widgets with text-only and hybrid (image + text) support.
  • Interstitial Ads: Full-screen ads with session-aware frequency capping.
  • Native Ads: Builder-pattern widgets for completely custom UI.
  • Session Tracking: Built-in session counting to power sophisticated targeting.
  • Advanced Frequency Capping: Scheduling, max views per session, and minimum session count support.
  • User Identification: Support for appUserId to track unique users across devices.
  • Analytics: Built-in tracking for impressions and clicks with support for custom user IDs.
  • Smart Targeting Metadata: Automatic capture of app version, device language, and specific hardware models.
  • Offline Reliability: Batch analytics events locally when offline and sync when network connectivity is restored.

Installation #

Add smartlinks_ad to your pubspec.yaml:

dependencies:
  smartlinks_ad:
    git:
      url: https://gitlab.com/elmansoryanas/smartlinks_ad.git
      ref: main

Usage #

1. Initialize the SDK #

Initialize the service with your API Key in your main.dart or before using any ad widgets.

import 'package:smartlinks_ad/smartlinks_ad.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // (Optional) Initialize Firebase BEFORE smartlinks_ad if you want Push Notifications
  // await Firebase.initializeApp();

  // Initialize the ad service with optional user ID
  final adService = SmartLinksAd();
  await adService.initialize(
    'YOUR_API_KEY',
    appUserId: 'user_123_abc', // Optional: track unique users
  );

  // Initialize Push Handler (requires Firebase to be initialized)
  // See "Push Notifications Setup" below for more details.
  await SmartLinksPushHandler.initialize(apiKey: 'YOUR_API_KEY');

  runApp(MyApp());
}

Note: You can obtain the API Key from the Linklytics Dashboard (Profile Settings -> API Keys).

Update User ID Dynamically #

If the user logs in after initialization, you can update the appUserId at any time:

SmartLinksAd().setAppUserId('new_user_999');

2. Banner Ad #

Display a banner ad anywhere in your widget tree.

SmartLinkBannerAd(
  adService: adService,
  height: 100, // Optional: override default height for the selected banner size
  fit: BoxFit.cover, // Optional: default is BoxFit.cover
)

3. Interstitial Ad #

Interstitial ads are full-screen ads that cover the interface of their host app.

// Create an instance
final interstitial = SmartLinkInterstitialAd(adService: adService);

// Load the ad
await interstitial.load();

// Check if loaded and show
if (interstitial.isLoaded) {
  interstitial.show(context, onDismissed: () {
    print('Ad dismissed');
  });
}

4. Native Ad #

Native ads allow you to customize the look and feel of the ads to match your app's design.

SmartLinkNativeAd(
  adService: adService,
  builder: (context, ad) {
    return Container(
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [BoxShadow(blurRadius: 4, color: Colors.black12)],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(ad.name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
          SizedBox(height: 8),
          if (ad.config['image_url'] != null)
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Image.network(ad.config['image_url'], height: 150, width: double.infinity, fit: BoxFit.cover),
            ),
          SizedBox(height: 8),
          Text(ad.config['description'] ?? '', style: TextStyle(fontSize: 14)),
          SizedBox(height: 8),
          ElevatedButton(
            onPressed: () => ad.handleClick(context), // Handle click tracking and navigation
            child: Text(ad.config['cta_text'] ?? 'Learn More'),
          ),
        ],
      ),
    );
  },
)

5. Push Notification Ads Setup #

SmartLinks supports delivering rich push notification ads dynamically.

Prerequisites: Your app must have Firebase Cloud Messaging (FCM) configured.

A. Set Up the Background Handler Create a top-level function in your main.dart to handle background messages:

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  await SmartLinksPushHandler.handleBackgroundMessage(message);
}

B. Initialize Push Handling In your main() method, register the background handler, request permissions, and listen for foreground messages:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  await FirebaseMessaging.instance.requestPermission();

  // (Optional) Retrieve appUserId (e.g. from linklytics_flutter)
  // final appUserId = await LinklyticsFlutter().getAppUserId();

  await SmartLinksPushHandler.initialize(
    apiKey: 'YOUR_API_KEY',
    appUserId: appUserId, // Optional: associates push token with user ID
  );

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    SmartLinksPushHandler.handleForegroundMessage(message);
  });

  runApp(const MyApp());
}

(Optional) Forwarding Tap Events from Custom Local Notifications If your app already uses flutter_local_notifications, forward the tap payload to ensure SmartLinks can process ad clicks:

void onNotificationTapped(NotificationResponse response) {
  final payload = response.payload;
  if (payload != null) {
    SmartLinksPushHandler.processNotificationPayload(payload);
  }
}

Requirements #

  • Flutter >=3.3.0
  • Dart >=3.0.0

License #

MIT