flutter_kalapa_bsdk 1.0.10
flutter_kalapa_bsdk: ^1.0.10 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:io';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:flutter_kalapa_bsdk/kalapa_behavior_score_flutter.dart';
import 'package:flutter_kalapa_bsdk/kalapa_behavior_score_flutter_method_channel.dart';
import 'package:flutter_kalapa_bsdk/kalapa_behavior_score_flutter_platform_interface.dart';
import 'app_bar_item.dart';
import 'consent_manager.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MaterialApp(
home: MyHomePage(title: 'Kalapa Behavior Score Example')));
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
final TextEditingController _phoneController = KalapaTextEditingController();
double _loanAmount = 1000000;
final klpBehaviorScore = KalapaBehaviorScoreFlutter();
final _consentManager = ConsentManager();
var _isMobileAdsInitializeCalled = false;
var _isPrivacyOptionsRequired = false;
BannerAd? _bannerAd;
BannerAd? _middleBannerAd;
bool _isLoaded = false;
bool _isMiddleBannerLoaded = false;
Orientation? _currentOrientation;
final String _adUnitId = Platform.isAndroid
? 'ca-app-pub-3940256099942544/9214589741'
: 'ca-app-pub-3940256099942544/2435281174';
@override
void initState() {
super.initState();
klpBehaviorScore.startTracking(true);
_consentManager.gatherConsent((consentGatheringError) {
if (consentGatheringError != null) {
// Consent not obtained in current session.
debugPrint(
"${consentGatheringError.errorCode}: ${consentGatheringError.message}",
);
}
// Check if a privacy options entry point is required.
_getIsPrivacyOptionsRequired();
// Attempt to initialize the Mobile Ads SDK.
_initializeMobileAdsSDK();
});
// This sample attempts to load ads using consent obtained in the previous session.
_initializeMobileAdsSDK();
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
Future<void> collectFunction() async {
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");
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
actions: _appBarActions(),
),
body: OrientationBuilder(
builder: (context, orientation) {
if (_currentOrientation != orientation) {
if (_currentOrientation != null) {
_isLoaded = false;
_isMiddleBannerLoaded = false;
_loadAd();
_loadMiddleAd();
}
_currentOrientation = orientation;
}
return Stack(
children: [
SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const SizedBox(height: 20),
TextField(
controller: _phoneController,
keyboardType: TextInputType.phone,
decoration: const InputDecoration(
labelText: 'Phone Number',
border: OutlineInputBorder(),
),
key: const Key('klp_phone_number'),
),
const SizedBox(height: 20),
Text(
'Loan Amount: ${_loanAmount.toStringAsFixed(0)}',
style: Theme.of(context).textTheme.titleMedium,
),
Slider(
value: _loanAmount,
min: 1000000,
max: 10000000,
divisions: 90,
key: const Key('klp_loan_amount'),
onChanged: (value) {
setState(() {
_loanAmount = value;
});
},
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
klpBehaviorScore
.addModule(KLPApplicationModule())
.addModule(KLPBehaviorModule())
.addModule(KLPCalendarModule())
.addModule(
KLPContactsModule(
collectFullInformation: true),
)
.addModule(KLPMusicModule())
.addModule(KLPMediaModule())
.addModule(KLPReminderModule())
.addModule(KLPCoreModule())
.addModule(KLPLocationModule())
.build(
"f93b9ddb85e2429bb9c82e12b719b5b9",
"kalapa-flutter-sdk-test-123456",
);
await collectFunction();
klpBehaviorScore.stopTracking();
},
key: const Key('finish'),
child: const Text('Finish'),
),
const SizedBox(height: 20),
if (_middleBannerAd != null && _isMiddleBannerLoaded)
Container(
width: _middleBannerAd!.size.width.toDouble(),
height: _middleBannerAd!.size.height.toDouble(),
child: AdWidget(ad: _middleBannerAd!),
),
],
),
),
),
if (_bannerAd != null && _isLoaded)
Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
child: SizedBox(
width: _bannerAd!.size.width.toDouble(),
height: _bannerAd!.size.height.toDouble(),
child: AdWidget(ad: _bannerAd!),
),
),
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
);
}
List<Widget> _appBarActions() {
var array = [AppBarItem(AppBarItem.adInpsectorText, 0)];
if (_isPrivacyOptionsRequired) {
array.add(AppBarItem(AppBarItem.privacySettingsText, 1));
}
return <Widget>[
PopupMenuButton<AppBarItem>(
itemBuilder: (context) => array
.map(
(item) => PopupMenuItem<AppBarItem>(
value: item,
child: Text(item.label),
),
)
.toList(),
onSelected: (item) {
switch (item.value) {
case 0:
MobileAds.instance.openAdInspector((error) {
// Error will be non-null if ad inspector closed due to an error.
});
case 1:
_consentManager.showPrivacyOptionsForm((formError) {
if (formError != null) {
debugPrint("${formError.errorCode}: ${formError.message}");
}
});
}
},
),
];
}
/// Loads and shows a banner ad.
///
/// Dimensions of the ad are determined by the width of the screen.
void _loadAd() async {
// Only load an ad if the Mobile Ads SDK has gathered consent aligned with
// the app's configured messages.
var canRequestAds = await _consentManager.canRequestAds();
if (!canRequestAds) {
return;
}
if (!mounted) {
return;
}
// Get an AnchoredAdaptiveBannerAdSize before loading the ad.
final size = await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
MediaQuery.sizeOf(context).width.truncate(),
);
if (size == null) {
// Unable to get width of anchored banner.
return;
}
BannerAd(
adUnitId: _adUnitId,
request: const AdRequest(),
size: size,
listener: BannerAdListener(
// Called when an ad is successfully received.
onAdLoaded: (ad) {
setState(() {
_bannerAd = ad as BannerAd;
_isLoaded = true;
});
},
// Called when an ad request failed.
onAdFailedToLoad: (ad, err) {
ad.dispose();
},
// Called when an ad opens an overlay that covers the screen.
onAdOpened: (Ad ad) {},
// Called when an ad removes an overlay that covers the screen.
onAdClosed: (Ad ad) {},
// Called when an impression occurs on the ad.
onAdImpression: (Ad ad) {},
),
).load();
}
void _loadMiddleAd() async {
var canRequestAds = await _consentManager.canRequestAds();
if (!canRequestAds) {
return;
}
if (!mounted) {
return;
}
final size = await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
MediaQuery.sizeOf(context).width.truncate(),
);
if (size == null) {
return;
}
BannerAd(
adUnitId: _adUnitId,
request: const AdRequest(),
size: size,
listener: BannerAdListener(
onAdLoaded: (ad) {
setState(() {
_middleBannerAd = ad as BannerAd;
_isMiddleBannerLoaded = true;
});
},
onAdFailedToLoad: (ad, err) {
ad.dispose();
},
onAdOpened: (Ad ad) {},
onAdClosed: (Ad ad) {},
onAdImpression: (Ad ad) {},
),
).load();
}
/// Redraw the app bar actions if a privacy options entry point is required.
void _getIsPrivacyOptionsRequired() async {
if (await _consentManager.isPrivacyOptionsRequired()) {
setState(() {
_isPrivacyOptionsRequired = true;
});
}
}
/// Initialize the Mobile Ads SDK if the SDK has gathered consent aligned with
/// the app's configured messages.
void _initializeMobileAdsSDK() async {
if (_isMobileAdsInitializeCalled) {
return;
}
if (await _consentManager.canRequestAds()) {
_isMobileAdsInitializeCalled = true;
// Initialize the Mobile Ads SDK.
await MobileAds.instance.initialize();
// Load an ad.
_loadAd();
_loadMiddleAd();
}
}
@override
void dispose() {
_bannerAd?.dispose();
_middleBannerAd?.dispose();
super.dispose();
}
}