osmos_flutter_plugin 2.0.1
osmos_flutter_plugin: ^2.0.1 copied to clipboard
Flutter Plugin for the OSMOS Ad Fetching, Ad Rendering and Event Tracking.
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:osmos_flutter_plugin/ads/views/banner_ad_widget.dart';
import 'package:osmos_flutter_plugin/ads/views/interstitial_ad_view.dart';
import 'package:osmos_flutter_plugin/core/osmos_sdk.dart';
import 'package:osmos_flutter_plugin/models/targetingParams.dart';
import 'package:osmos_flutter_plugin/models/trackingParams.dart';
import 'dart:async';
/// Main entry point of the OSMOS Flutter Plugin Example
///
/// This example demonstrates the core functionality of the OSMOS SDK:
/// 1. SDK Initialization
/// 2. Ad Fetching using AdFetcher
/// 3. Event Registration using RegisterEvent
/// 4. Banner Ad Display using BannerAdView
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize OSMOS SDK globally with your configuration
// Replace "10088010" with your actual client ID
await OsmosSDK.clientId("10088010")
.debug(true) // Enable debug mode for development
.productAdsHost("demo.o-s.io") // PLA (Product Listing Ads) server
.displayAdsHost("demo-ba.o-s.io") // Display ads server
.eventTrackingHost("t.o-s.io") // Event tracking server
.buildGlobalInstance(); // Create global SDK instance
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home:
const OsmosAdExample(), // Use the comprehensive example for plugin release
);
}
}
/// Simple example demonstrating OSMOS Flutter Plugin core functionality
///
/// This widget demonstrates the three main steps:
/// 1. Fetch ads from OSMOS servers
/// 2. Register user events for analytics
/// 3. Display banner ads with interaction callbacks
class OsmosAdExample extends StatefulWidget {
const OsmosAdExample({super.key});
@override
State<OsmosAdExample> createState() => _OsmosAdExampleState();
}
class _OsmosAdExampleState extends State<OsmosAdExample> {
late OsmosSDK sdk; // Global SDK instance
Future<Map<String, dynamic>?>? adData; // Future for loading initial ad data
Map<String, dynamic>? result; // Result from fetch ads button
bool isLoading = false; // Loading state for fetch button
final String userId = "user_12345"; // Sample user ID for demo
@override
void initState() {
super.initState();
// Get the global SDK instance initialized in main()
sdk = OsmosSDK.globalInstance();
// Load initial ad data for display section
adData = loadAdData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('OSMOS Plugin Example'),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// STEP 1: Ad Fetcher Section
// Demonstrates how to fetch display ads with targeting parameters
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
const Text('1. Fetch Ads',
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
ElevatedButton(
onPressed: isLoading ? null : _fetchAds,
child: isLoading
? const CircularProgressIndicator()
: const Text('Fetch Display Ads'),
),
if (result != null)
Text('✅ Ad fetched successfully!',
style: TextStyle(color: Colors.green)),
],
),
),
),
const SizedBox(height: 16),
// STEP 2: Event Registration Section
// Shows how to register user events for analytics and tracking
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
const Text('2. Register Events',
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: _registerViewEvent,
child: const Text('Register Ad Click'),
),
],
),
],
),
),
),
const SizedBox(height: 16),
// STEP 3: Ad Display Section
// Demonstrates how to display banner ads with click/impression callbacks
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
const Text('3. Display Banner Ad',
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
Container(
height: 120,
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8),
),
child: FutureBuilder<Map<String, dynamic>?>(
future: adData,
builder: (context, snapshot) {
// Show loading indicator while fetching ad data
if (snapshot.connectionState ==
ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator());
}
// Handle errors during ad loading
if (snapshot.hasError) {
return Center(
child: Text("Error: ${snapshot.error}"));
}
final data = snapshot.data;
// Show message if no ad data is available
if (data == null || data.isEmpty) {
return const Center(
child: Text("No ad data found."));
}
// Display the banner ad using BannerAdView
return sdk.bannerAdView.showAd(
adData: data,
height: 120,
width: double.infinity,
onAdClick: (data) {
// Handle ad click event
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ad clicked!')),
);
},
onViewAppeared: (data, url) {
// Handle ad impression event
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ad appeared!')),
);
},
);
})),
],
),
),
),
const SizedBox(height: 10),
// STEP 3: Ad Display Section
// Demonstrates how to display interstitial ads
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
const Text('4. Display Interstitial Ad',
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.bold)),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _showAd,
child: const Text('Interstitial Ad'),
),
],
),
),
),
],
),
),
);
}
/// Load initial ad data for the display section
/// Uses AdRenderer to fetch banner ads with basic parameters
Future<Map<String, dynamic>?> loadAdData() async {
final data = await sdk.adRenderer.fetchBannerAdsWithAu(
cliUbid: "xyz", // Client user identifier
pageType: "demo_page", // Page context for ad targeting
adUnit: "banner_ads"); // Ad unit/placement name
return data;
}
/// Fetch display ads using AdFetcher with targeting parameters
/// Demonstrates advanced ad fetching with context and geo targeting
Future<void> _fetchAds() async {
setState(() => isLoading = true);
try {
// Example: Create on-demand SDK instance (optional)
// You can also use the global SDK instance instead
var osmosSdk = await OsmosSDK.clientId("10088010").debug(false).build();
// Set up targeting parameters for more relevant ads
var context =
ContextTargeting.keyword("potato chips"); // Keyword targeting
var geo = GeoTargeting.location(
city: "pune", country: "india"); // Location targeting
// Fetch display ads with targeting parameters
var response = await osmosSdk.adFetcher.fetchDisplayAdsWithAu(
cliUbid: "xyz",
// Client user identifier
pageType: "demo_page",
// Page type for context
productCount: 10,
// Maximum number of ads to fetch
adUnits: ["banner_ads"],
// List of ad units to fetch
targetingParams: [context, geo]); // Targeting parameters
setState(() {
result = response;
});
} catch (e) {
// Handle errors gracefully with user feedback
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error fetching ads: $e')),
);
} finally {
setState(() => isLoading = false);
}
}
/// Fetching and displaying Interstitial Ad
Future _showAd() async {
var osmosSdk = OsmosSDK.globalInstance();
osmosSdk.adRenderer
.fetchBannerAdsWithAu(
cliUbid: "xyz",
pageType: "demo_page",
adUnit: "video_banner_ads",
)
.then((value) async {
if (value != null) {
await sdk.interstitialAdView.showAd(adData: value, alignment: "center");
}
});
}
/// Register ad click event with tracking parameters
/// Demonstrates how to track user interactions for analytics
Future<void> _registerViewEvent() async {
try {
// Build tracking parameters with additional context
var params = TrackingParams.builder()
.videoViewSec(4) // Video view duration
.skuId("value") // Product SKU if applicable
.build();
var sdk = OsmosSDK.globalInstance();
// Register ad click event for analytics
await sdk.registerEvent.registerAdClickEvent(
cliUbid: "c367af54c74705",
// Client user identifier
uclid: "21680792159968|2777510___Astore___Anet..",
// Unique content/ad identifier
trackingParams: params, // Additional tracking parameters
);
// Provide user feedback on successful event registration
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Ad click event registered!')),
);
} catch (e) {
// Handle errors and show user-friendly error message
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error: $e')),
);
}
}
}