flutter_kalapa_bsdk 1.0.9 copy "flutter_kalapa_bsdk: ^1.0.9" to clipboard
flutter_kalapa_bsdk: ^1.0.9 copied to clipboard

A Flutter plugin designed to capture a client’s digital footprint from both iOS and Android devices and upload it to the Kalapa service for future processing of scorecards and fragments. It provides a [...]

example/lib/main.dart

import 'dart:math';
import 'dart:io';

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

import 'package:flutter/services.dart';
import 'package:flutter_kalapa_bsdk/kalapa_behavior_score_flutter.dart';
import 'package:flutter_kalapa_bsdk/kalapa_behavior_score_flutter_platform_interface.dart';
import 'package:flutter_kalapa_bsdk/kalapa_behavior_score_widget.dart';
import 'package:kalapa_behavior_score_flutter_example/backend.dart';

import 'package:google_mobile_ads/google_mobile_ads.dart'; // <-- Add this import

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileAds.instance.initialize(); // <-- Initialize Mobile Ads
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  static Environment appEnv = Environment.prod;

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final klpBehaviorScore = KalapaBehaviorScoreFlutter();
  final GlobalKey<KalapaBannerViewState> _bannerKey =
      GlobalKey<KalapaBannerViewState>();

  BannerAd? _admobBannerAd; // <-- AdMob Banner instance
  bool _admobBannerLoaded = false;

  // Replace with your own Ad Unit ID in production!
  final String _admobBannerAdUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/6300978111'
      : 'ca-app-pub-3940256099942544/2934735716';

  @override
  void initState() {
    super.initState();
    initPlatformState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _bannerKey.currentState?.load();
    });
    _loadAdMobBanner(); // <-- Load AdMob Banner
  }

  void _loadAdMobBanner() {
    final size = AdSize.banner;
    final banner = BannerAd(
      adUnitId: _admobBannerAdUnitId,
      size: size,
      request: const AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (ad) {
          setState(() {
            _admobBannerAd = ad as BannerAd;
            _admobBannerLoaded = true;
          });
        },
        onAdFailedToLoad: (ad, error) {
          ad.dispose();
          setState(() {
            _admobBannerLoaded = false;
          });
        },
      ),
    );
    banner.load();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await klpBehaviorScore.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    if (!mounted) return;
    setState(() {
      _platformVersion = platformVersion;
    });
  }

  void buildFunction() {
    print("🪫 Build button Pressed! Function buildFunction triggered.");
    final String uuid = getUUID();
    final bool isDevelopment = MyApp.appEnv == Environment.dev;
    klpBehaviorScore
        .addModule(KLPApplicationModule())
        .addModule(KLPBehaviorModule())
        .addModule(KLPCalendarModule())
        .addModule(KLPContactsModule(collectFullInformation: true))
        .addModule(KLPMusicModule())
        .addModule(KLPMediaModule())
        .addModule(KLPReminderModule())
        .addModule(KLPCoreModule())
        .addModule(KLPLocationModule())
        .switchEnvironment(isDevelopment)
        .build(MyApp.appEnv.appKey, uuid);
    klpBehaviorScore.startTracking(true);
  }

  Future<void> collectFunction() async {
    print("🚀 Collect Pressed! Function collectFunction triggered.");
    try {
      KLPBehaviorScoreResult? result = await klpBehaviorScore.collect();
      if (result != null) {
        print("✅ Collect Completed! Result: ${result.toJson()}");
      } else {
        print("⚠️ Collect returned null.");
      }
    } catch (e) {
      print("❌ Error during collect: $e");
    }
    klpBehaviorScore.stopTracking();
  }

  String getUUID() {
    final Random random = Random.secure();
    final List<int> bytes = List.generate(16, (_) => random.nextInt(256));
    bytes[6] = (bytes[6] & 0x0F) | 0x40;
    bytes[8] = (bytes[8] & 0x3F) | 0x80;
    return '${_bytesToHex(bytes.sublist(0, 4))}-'
        '${_bytesToHex(bytes.sublist(4, 6))}-'
        '${_bytesToHex(bytes.sublist(6, 8))}-'
        '${_bytesToHex(bytes.sublist(8, 10))}-'
        '${_bytesToHex(bytes.sublist(10, 16))}';
  }

  String _bytesToHex(List<int> bytes) {
    return bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
  }

  @override
  void dispose() {
    _admobBannerAd?.dispose(); // <-- Dispose AdMob Banner
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Stack(
          children: [
            // Main content
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('Running on: $_platformVersion\n'),
                  const SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: buildFunction,
                    key: const Key("flutter_tracking_btn"),
                    child: const Text("Build 🪫"),
                  ),
                  KalapaBehaviorScoreWidget(data: "Hello"),
                  KalapaBannerView(
                    key: _bannerKey,
                    adUnitID: "b1a8a5f3-8cb0-4463-a69b-366ce610b255",
                    adSize: BannerSize.adaptiveBanner(
                        MediaQuery.of(context).size.width),
                    delegate: MyBannerDelegate(),
                  ),
                  ElevatedButton(
                    onPressed: collectFunction,
                    key: const Key("flutter_collect_btn"),
                    child: const Text("Collect 🚀"),
                  ),
                ],
              ),
            ),
            // AdMob Banner at the bottom
            if (_admobBannerAd != null && _admobBannerLoaded)
              Align(
                alignment: Alignment.bottomCenter,
                child: SafeArea(
                  child: SizedBox(
                    width: _admobBannerAd!.size.width.toDouble(),
                    height: _admobBannerAd!.size.height.toDouble(),
                    child: AdWidget(ad: _admobBannerAd!),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

enum Environment { prod, dev }

extension EnvironmentExtension on Environment {
  String get appKey {
    switch (this) {
      case Environment.prod:
        return "<<YOUR_PROD_KEY>>";
      case Environment.dev:
        return "<<YOUR_DEV_KEY>>";
    }
  }
}

class MyBannerDelegate extends BannerViewDelegate {
  final BackEndService _service = BackEndService();

  @override
  void onAdReceived(KalapaBannerView bannerView, String adId) {
    print("Function onAdReceived called");
    _service.logAds(
      adId: adId,
      adUnitId: bannerView.adUnitID,
      eventType: 'loaded',
    );
  }

  @override
  void onAdFailedToLoad(
      KalapaBannerView bannerView, String adId, BannerError error) {
    print("Function onAdFailedToLoad called with error: $error");
    _service.logAds(
      adId: adId,
      adUnitId: bannerView.adUnitID,
      eventType: 'failed',
    );
  }

  @override
  void onAdClicked(KalapaBannerView bannerView, String adId) {
    print("Function onAdClicked called");
    _service.logAds(
      adId: adId,
      adUnitId: bannerView.adUnitID,
      eventType: 'clicked',
    );
  }

  @override
  void onAdImpression(KalapaBannerView bannerView, String adId) {
    print("Function onAdImpression called");
    _service.logAds(
      adId: adId,
      adUnitId: bannerView.adUnitID,
      eventType: 'shown',
    );
  }

  @override
  void onAdScreenAppeared(KalapaBannerView bannerView, String adId) {
    print("Function onAdScreenAppeared called");
    _service.logAds(
      adId: adId,
      adUnitId: bannerView.adUnitID,
      eventType: 'opened',
    );
  }

  @override
  void onAdScreenDismissed(KalapaBannerView bannerView, String adId) {
    print("Function onAdScreenDismissed called");
    _service.logAds(
      adId: adId,
      adUnitId: bannerView.adUnitID,
      eventType: 'closed',
    );
  }
}
2
likes
0
points
33
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin designed to capture a client’s digital footprint from both iOS and Android devices and upload it to the Kalapa service for future processing of scorecards and fragments. It provides a seamless API for integrating digital footprint collection into Flutter applications, ensuring cross-platform compatibility.

Homepage

License

unknown (license)

Dependencies

flutter, google_mobile_ads, http, plugin_platform_interface, webview_flutter

More

Packages that depend on flutter_kalapa_bsdk

Packages that implement flutter_kalapa_bsdk