securiti_consent_sdk 1.154.0
securiti_consent_sdk: ^1.154.0 copied to clipboard
A Flutter plugin for managing user consent preferences and compliance with privacy regulations. Integrates with Securiti's Consent Management Platform.
consent_sdk_plugin #
A Flutter plugin for managing user consent preferences and compliance with privacy regulations. Integrates with Securiti's Consent Management Platform.
Requirements #
- iOS 15.0+
- Android API 24+ (Android 7.0+)
- Flutter 3.0.0+
- Dart 3.0.0+
Table of Contents #
- Installation
- Setup
- Updating Dependencies
- Basic Usage
- API Reference
- Google Consent Mode Integration
- IAB Europe TCF Integration
- Data Models
- Example App
Installation #
Add this to your package's pubspec.yaml file:
dependencies:
securiti_consent_sdk: ^1.0.0
Then run:
flutter pub get
Setup #
Android Setup #
- Add the Securiti Maven repository to your
android/app/build.gradle:
repositories {
google()
mavenCentral()
maven {
url 'https://cdn-prod.securiti.ai/consent/maven'
}
}
- Ensure your
MainActivityextendsFlutterFragmentActivity:
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity: FlutterFragmentActivity() {
}
-
Minimum Requirements:
- Android API Level 24+ (Android 7.0)
- Kotlin 1.9.22+
- Gradle 8.2.2+
-
Key Dependencies (automatically included by the plugin):
- Securiti Consent SDK:
1.141.0(includes Google Consent Mode support) - Kotlin Coroutines:
1.7.3 - AndroidX Lifecycle:
2.6.2 - AndroidX Activity:
1.8.1
- Securiti Consent SDK:
iOS Setup #
On iOS the plugin is distributed through Swift Package Manager (SPM) only. CocoaPods trunk becomes read-only on December 2, 2026, so the plugin no longer ships a podspec, and the native ConsentUI framework is resolved from mobile-consent-sdk-ios.
- Enable Swift Package Manager (Flutter 3.24+):
flutter config --enable-swift-package-manager
With SPM disabled, flutter build ios stops with "Plugin securiti_consent_sdk is only Swift Package Manager compatible".
- Build or run the app. Flutter adds the plugin's Swift package to your Xcode project automatically. You don't need to run
pod installor edit a Podfile for this plugin:
flutter run -d ios
Other plugins in your app that don't support SPM yet still install through CocoaPods. Flutter handles both side by side.
-
Set your iOS deployment target to 15.0 or higher. In Xcode, open
Runner> General > Minimum Deployments. -
Minimum Requirements:
- iOS 15.0+
- Flutter 3.24+
- Swift 5.9+
- Xcode 15.0+
-
Key Dependencies (included automatically by the plugin through SPM):
- Securiti ConsentUI, pinned to the same version as the plugin (includes Google Consent Mode support)
-
For Firebase Analytics or Google Mobile Ads integration, add the Flutter plugins (
firebase_analytics,google_mobile_ads) topubspec.yaml. They bring in the native iOS SDKs, so you don't need extra Podfile entries.
Updating Dependencies #
Updating to Latest Version #
To update the Securiti Consent SDK to the latest version:
- Update pubspec.yaml:
dependencies:
securiti_consent_sdk: ^1.141.0 # Update to latest version
- For Android - Manual Update (if needed):
If you need to use a specific version of the Android SDK, you can override it in your app's android/app/build.gradle:
dependencies {
// Your other dependencies
// Override Securiti Consent SDK version
implementation('ai.securiti.cmpsdkcore:consent-sdk:1.141.0') {
force = true
}
}
- For iOS:
The iOS ConsentUI version is pinned by the plugin's Swift package, so upgrading securiti_consent_sdk in pubspec.yaml also upgrades the native SDK. To pull a new version, run:
flutter pub upgrade securiti_consent_sdk
flutter clean && flutter run -d ios
Version Compatibility #
| Flutter Plugin | Android SDK | iOS SDK | Google Consent Mode |
|---|---|---|---|
| 1.141.0+ | 1.141.0+ | 1.1.141.0+ | ✅ Supported |
| 1.140.0 | 1.140.0 | 1.1.140.0 | ✅ Supported |
| < 1.140.0 | < 1.140.0 | < 1.1.140.0 | ❌ Not Supported |
Firebase and Google Ads SDK Compatibility #
For best results with Google Consent Mode integration:
Android:
dependencies {
// Firebase Analytics
implementation 'com.google.firebase:firebase-analytics:21.5.0'
// Google Mobile Ads (if using AdMob)
implementation 'com.google.android.gms:play-services-ads:22.6.0'
}
iOS: the Flutter plugins below bring in the native Firebase and Google Mobile Ads SDKs.
Flutter (pubspec.yaml):
dependencies:
# Firebase Analytics
firebase_analytics: ^10.7.4
# Google Mobile Ads (if using AdMob)
google_mobile_ads: ^4.0.0
Basic Usage #
1. Import the Package #
import 'package:securiti_consent_sdk/consent_sdk_plugin.dart';
import 'package:securiti_consent_sdk/cmp_sdk_options.dart';
import 'package:securiti_consent_sdk/models/consent_status.dart';
2. Initialize the SDK #
final _consentSdkPlugin = ConsentSdkPlugin();
void initializeSDK() {
CmpSDKOptions options = CmpSDKOptions(
appURL: 'https://your-app-url.securiti.xyz',
cdnURL: 'https://your-cdn-url.securiti.xyz',
tenantID: 'your-tenant-id',
appID: 'your-app-id',
testingMode: true,
loggerLevel: CmpSDKLoggerLevel.debug,
consentsCheckInterval: 60,
subjectId: 'user-123',
languageCode: 'en',
locationCode: 'US',
);
_consentSdkPlugin.setupSDK(options.toMap());
}
3. Listen for SDK Readiness #
import 'package:flutter/services.dart';
static const EventChannel _eventChannel =
EventChannel('ai.securiti.consent_sdk_plugin/isSDKReady');
void listenForSDKReady() {
_eventChannel.receiveBroadcastStream().listen((event) {
bool isReady = event as bool;
if (isReady) {
print('SDK is ready');
_consentSdkPlugin.presentConsentBanner();
}
});
}
4. Present Consent UI #
// Show consent banner
_consentSdkPlugin.presentConsentBanner();
// Show preference center
_consentSdkPlugin.presentPreferenceCenter();
API Reference #
Initialization #
setupSDK(Map options)
Initializes the Consent SDK with configuration options.
Parameters:
options: Map containing SDK configuration (useCmpSDKOptions.toMap())
Example:
CmpSDKOptions options = CmpSDKOptions(
appURL: 'https://your-app.securiti.xyz',
cdnURL: 'https://your-cdn.securiti.xyz',
tenantID: 'tenant-123',
appID: 'app-456',
testingMode: false,
loggerLevel: CmpSDKLoggerLevel.info,
consentsCheckInterval: 3600,
subjectId: 'user-id',
languageCode: 'en',
locationCode: 'US',
);
_consentSdkPlugin.setupSDK(options.toMap());
UI Methods #
presentConsentBanner()
Displays the consent banner to the user.
Example:
_consentSdkPlugin.presentConsentBanner();
presentPreferenceCenter()
Displays the preference center for managing consent settings.
Example:
_consentSdkPlugin.presentPreferenceCenter();
Consent Management #
getConsent(dynamic identifier)
Gets the consent status for a specific purpose or permission.
Parameters:
identifier: Either anint(purpose ID) orString(permission ID)
Returns: Future<ConsentStatus>
Example:
// Get consent for a purpose
ConsentStatus purposeConsent = await _consentSdkPlugin.getConsent(123);
// Get consent for a permission
ConsentStatus permissionConsent = await _consentSdkPlugin.getConsent('location');
if (purposeConsent == ConsentStatus.granted) {
// Consent is granted
}
getPurposes()
Retrieves all purposes defined in the consent configuration.
Returns: Future<List<Purpose>>
Example:
List<Purpose> purposes = await _consentSdkPlugin.getPurposes();
for (Purpose purpose in purposes) {
print('Purpose: ${purpose.purposeName}');
print('Status: ${purpose.consentStatus}');
}
getPermissions()
Retrieves all app permissions defined in the consent configuration.
Returns: Future<List<AppPermission>>
Example:
List<AppPermission> permissions = await _consentSdkPlugin.getPermissions();
for (AppPermission permission in permissions) {
print('Permission: ${permission.name}');
print('Status: ${permission.consentStatus}');
}
getSdksInPurpose(int purposeId)
Gets all SDKs associated with a specific purpose.
Parameters:
purposeId: The purpose ID
Returns: Future<List<dynamic>>
Example:
List<dynamic> sdks = await _consentSdkPlugin.getSdksInPurpose(123);
setConsent(dynamic entity, ConsentStatus status)
Sets the consent status for a purpose or permission.
Parameters:
entity: Either aPurposeorAppPermissionobjectstatus: The consent status to set
Returns: Future<void>
Example:
// Set consent for a purpose
Purpose purpose = purposes.first;
await _consentSdkPlugin.setConsent(purpose, ConsentStatus.granted);
// Set consent for a permission
AppPermission permission = permissions.first;
await _consentSdkPlugin.setConsent(permission, ConsentStatus.declined);
resetConsents()
Resets all stored consents to their default state.
Returns: Future<void>
Example:
await _consentSdkPlugin.resetConsents();
Configuration #
getBannerConfig([MainConfiguration? cdn])
Gets the banner configuration.
Parameters:
cdn: Optional CDN configuration
Returns: Future<BannerConfig?>
Example:
BannerConfig? config = await _consentSdkPlugin.getBannerConfig();
if (config != null) {
print('Banner heading: ${config.bannerHeading}');
print('Accept button text: ${config.accept}');
}
getSettingsPrompt()
Gets the settings prompt configuration.
Returns: Future<SettingsPrompt?>
Example:
SettingsPrompt? prompt = await _consentSdkPlugin.getSettingsPrompt();
if (prompt != null) {
print('Prompt heading: ${prompt.promptHeading}');
print('Permissions: ${prompt.permissions}');
}
uploadConsents(PostConsentsRequest request)
Uploads consent data to the server.
Parameters:
request: The consent data to upload
Returns: Future<bool>
Example:
PostConsentsRequest request = PostConsentsRequest(
uuid: 'user-123',
appUUID: 'app-456',
device: 'Android 12',
implicitConsent: false,
version: 1,
purposeConsents: [],
permissions: [],
isTestMode: false,
adId: 'advertising-id',
bannerInfo: 'Banner v1.0',
);
bool success = await _consentSdkPlugin.uploadConsents(request);
Google Consent Mode #
getGCMConsents()
Retrieves Google Consent Mode consent statuses for all configured Google consent types. Returns a map of Google Consent Types to ConsentStatus values.
Returns: Future<Map<GoogleConsentType, ConsentStatus>>
GoogleConsentType Enum Values:
GoogleConsentType.analyticsStorage- Controls consent for analytics cookies/storageGoogleConsentType.adStorage- Controls consent for advertising cookies/storageGoogleConsentType.adUserData- Controls consent for sending user data to GoogleGoogleConsentType.adPersonalization- Controls consent for personalized advertising
Example:
import 'package:securiti_consent_sdk/models/google_consent_type.dart';
import 'package:securiti_consent_sdk/models/consent_status.dart';
// Get GCM consents
Map<GoogleConsentType, ConsentStatus> gcmConsents = await _consentSdkPlugin.getGCMConsents();
// Access specific consent types
ConsentStatus analyticsConsent =
gcmConsents[GoogleConsentType.analyticsStorage] ?? ConsentStatus.notDetermined;
ConsentStatus adStorageConsent =
gcmConsents[GoogleConsentType.adStorage] ?? ConsentStatus.notDetermined;
// Check consent status
if (analyticsConsent == ConsentStatus.granted) {
print('Analytics storage is granted');
}
// Print all GCM consents
gcmConsents.forEach((type, status) {
print('${type.value}: ${status.value}');
});
Output Example:
analytics_storage: granted
ad_storage: declined
ad_user_data: granted
ad_personalization: declined
getGCMConfig()
Retrieves the Google Consent Mode configuration including purpose mappings and regional overrides.
Returns: Future<GcmConfig?>
Example:
import 'package:securiti_consent_sdk/models/gcm_config.dart';
// Get GCM configuration
GcmConfig? gcmConfig = await _consentSdkPlugin.getGCMConfig();
if (gcmConfig != null) {
// Check if GCM description should be shown
print('Show GCM Description: ${gcmConfig.showGcmDescription}');
// Access default purpose mappings
if (gcmConfig.defaultMapping != null) {
print('Analytics Storage Purpose IDs: ${gcmConfig.defaultMapping!.analyticsStorage}');
print('Ad Storage Purpose IDs: ${gcmConfig.defaultMapping!.adStorage}');
}
// Access regional overrides
if (gcmConfig.regionOverrides != null) {
gcmConfig.regionOverrides!.forEach((region, mapping) {
print('Region: $region - Analytics: ${mapping.analyticsStorage}');
});
}
}
For detailed GCM implementation guide, see: docs/GCM_IMPLEMENTATION_GUIDE.md
IAB Europe TCF #
These methods expose the IAB Europe Transparency & Consent Framework (TCF v2.2) data managed by the native SDKs. None of them throw: on a platform error they log with debugPrint and return false or null. See IAB Europe TCF Integration for a walkthrough.
import 'package:securiti_consent_sdk/models/iab_tcf_config.dart';
import 'package:securiti_consent_sdk/models/global_vendor_list.dart';
import 'package:securiti_consent_sdk/models/tcf_consents.dart';
isIabTcfEnabled()
Whether IAB Europe TCF is enabled for this app.
Returns: Future<bool>
Platform note: On iOS this reflects the published configuration only. On Android it is also
falsewhen the user's location is outside the configured TCF locations.
Example:
final bool tcfEnabled = await _consentSdkPlugin.isIabTcfEnabled();
getIabTcfConfig()
Returns the publisher's TCF configuration from the Securiti CDN: the purposes, features, stacks and vendors that are disclosed, plus the localized texts for the TCF banner and preference center.
Returns: Future<IabTcfConfig?>. This is null when TCF is not enabled. On Android it is also null when TCF doesn't apply at the user's location.
Example:
final IabTcfConfig? config = await _consentSdkPlugin.getIabTcfConfig();
if (config != null) {
print('Allowed vendors: ${config.allowedVendorIds}');
print('Consent purposes: ${config.purposeConsents}');
print('Legitimate interest purposes: ${config.purposeLegitimateInterests}');
print('Banner text (en): ${config.bannerText?['en']}');
}
getGlobalVendorList({bool forceRefresh = false})
Returns the latest IAB Global Vendor List (GVL v3), with Google's Ad Tech Provider list merged in. The list is checked once per app session. Pass forceRefresh: true to check again.
Returns: Future<GlobalVendorList?>. This is null when TCF isn't configured.
Example:
final GlobalVendorList? gvl = await _consentSdkPlugin.getGlobalVendorList();
if (gvl != null) {
print('GVL version: ${gvl.vendorListVersion}, policy: ${gvl.tcfPolicyVersion}');
final vendor = gvl.vendors[755];
if (vendor != null && !vendor.isDeleted) {
print('${vendor.name}: ${vendor.privacyPolicyUrl('en')}');
}
}
getIabPurposesTranslation(String languageCode, {bool forceRefresh = false})
Returns IAB's translation of the purposes, special purposes, features, special features, stacks and data categories into languageCode (for example "fr" or "pt-br"). Vendors are not included. Take vendor details from getGlobalVendorList().
Returns: Future<GlobalVendorList?>. This is null when IAB doesn't publish that language or TCF isn't configured. iOS also returns null for English, which is the vendor list's own language, so use getGlobalVendorList() for English texts.
Example:
final GlobalVendorList? fr = await _consentSdkPlugin.getIabPurposesTranslation('fr');
print(fr?.purposes[1]?.name); // Purpose 1's name in French
getTCString()
Returns the TC string stored on the device (IABTCF_TCString).
Returns: Future<String?>. This is null when no TC string has been stored yet.
Example:
final String? tcString = await _consentSdkPlugin.getTCString();
getTCFConsents()
Returns the TC data stored on the device, decoded into purpose, vendor and special-feature sets.
Returns: Future<TCFConsents?>. This is null when no TC data is stored.
Example:
final TCFConsents? consents = await _consentSdkPlugin.getTCFConsents();
if (consents != null) {
print('GDPR applies: ${consents.gdprApplies}');
print('Purpose 1 consent: ${consents.hasPurposeConsent(1)}');
print('Vendor 755 consent: ${consents.hasVendorConsent(755)}');
print('Additional Consent: ${consents.additionalConsent}');
}
setTCFChoices(TCFChoices choices)
Saves the user's TCF choices, typically collected by your own consent UI, and writes the standard IABTCF_* keys. Purposes and vendors that the publisher's configuration doesn't disclose are dropped.
This only stores the choices on the device. It does not upload anything.
Returns: Future<String?>. This is the new TC string, or null when TCF isn't configured or the vendor list couldn't be loaded.
Example:
final String? tcString = await _consentSdkPlugin.setTCFChoices(
TCFChoices(
purposeConsents: {1, 2, 3},
purposeLegitimateInterests: {2, 7},
specialFeatureOptIns: {1},
vendorConsents: {755},
vendorLegitimateInterests: {755},
googleAtpConsents: {89},
),
);
// Reject all: an empty TCFChoices saves "no consent" for everything
await _consentSdkPlugin.setTCFChoices(const TCFChoices());
Google Consent Mode Integration #
Google Consent Mode is a framework that allows you to adjust how Google tags behave based on user consent choices. The Securiti Consent SDK provides seamless integration with Google Consent Mode through the getGCMConsents() method.
Overview #
Google Consent Mode v2 requires mobile apps to signal user consent choices for four specific consent types:
- analytics_storage - Permission to store analytics data
- ad_storage - Permission to store advertising data
- ad_user_data - Permission to send user data to Google for advertising
- ad_personalization - Permission to use data for personalized ads
The SDK automatically maps your configured purposes to these Google consent types based on your Securiti platform configuration.
How It Works #
- Configure purpose-to-Google-consent-type mappings in your Securiti platform
- Initialize the SDK in your Flutter app
- Call
getGCMConsents()to retrieve mapped consent statuses - Pass the consent signals to Firebase Analytics or Google Ads SDKs
GCM Configuration #
Before using Google Consent Mode in your app, ensure you have configured the mappings in the Securiti Privacy Center:
- Navigate to your mobile app configuration
- Go to the Purposes section
- For each purpose, configure the Google Consent Mode mapping
- Select which Google consent type (analytics_storage, ad_storage, etc.) each purpose should map to
GCM Basic Usage #
import 'package:securiti_consent_sdk/consent_sdk_plugin.dart';
import 'package:securiti_consent_sdk/models/google_consent_type.dart';
import 'package:securiti_consent_sdk/models/consent_status.dart';
final _consentSdkPlugin = ConsentSdkPlugin();
Future<void> checkGoogleConsents() async {
try {
// Get GCM consents
Map<GoogleConsentType, Purpose> gcmConsents =
await _consentSdkPlugin.getGCMConsents();
// Check individual consent types
Purpose? analyticsConsent = gcmConsents[GoogleConsentType.analyticsStorage];
Purpose? adStorageConsent = gcmConsents[GoogleConsentType.adStorage];
Purpose? adUserDataConsent = gcmConsents[GoogleConsentType.adUserData];
Purpose? adPersonalizationConsent = gcmConsents[GoogleConsentType.adPersonalization];
// Log consent statuses
print('Analytics Storage: ${analyticsConsent?.consentStatus?.value}');
print('Ad Storage: ${adStorageConsent?.consentStatus?.value}');
print('Ad User Data: ${adUserDataConsent?.consentStatus?.value}');
print('Ad Personalization: ${adPersonalizationConsent?.consentStatus?.value}');
} catch (e) {
print('Error fetching GCM consents: $e');
}
}
Firebase Analytics Integration #
If you're using Firebase Analytics with Google Analytics 4, integrate consent signals:
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:securiti_consent_sdk/consent_sdk_plugin.dart';
import 'package:securiti_consent_sdk/models/google_consent_type.dart';
import 'package:securiti_consent_sdk/models/consent_status.dart';
final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
final _consentSdkPlugin = ConsentSdkPlugin();
Future<void> updateFirebaseConsent() async {
try {
// Get GCM consents from Securiti SDK
Map<GoogleConsentType, Purpose> gcmConsents =
await _consentSdkPlugin.getGCMConsents();
// Convert to boolean values
bool analyticsGranted = gcmConsents[GoogleConsentType.analyticsStorage]
?.consentStatus == ConsentStatus.granted;
bool adStorageGranted = gcmConsents[GoogleConsentType.adStorage]
?.consentStatus == ConsentStatus.granted;
bool adUserDataGranted = gcmConsents[GoogleConsentType.adUserData]
?.consentStatus == ConsentStatus.granted;
bool adPersonalizationGranted = gcmConsents[GoogleConsentType.adPersonalization]
?.consentStatus == ConsentStatus.granted;
// Set consent mode for Firebase Analytics
await _analytics.setConsent(
analyticsStorageConsentGranted: analyticsGranted,
adStorageConsentGranted: adStorageGranted,
adUserDataConsentGranted: adUserDataGranted,
adPersonalizationConsentGranted: adPersonalizationGranted,
);
print('Firebase consent updated successfully');
} catch (e) {
print('Error updating Firebase consent: $e');
}
}
Google Mobile Ads Integration #
For Google Mobile Ads (AdMob), handle consent before initializing ads:
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:securiti_consent_sdk/consent_sdk_plugin.dart';
import 'package:securiti_consent_sdk/models/google_consent_type.dart';
import 'package:securiti_consent_sdk/models/consent_status.dart';
final _consentSdkPlugin = ConsentSdkPlugin();
Future<void> initializeGoogleAds() async {
try {
// Get GCM consents
Map<GoogleConsentType, Purpose> gcmConsents =
await _consentSdkPlugin.getGCMConsents();
// Check if ad storage and ad personalization are granted
bool adStorageGranted = gcmConsents[GoogleConsentType.adStorage]
?.consentStatus == ConsentStatus.granted;
bool adPersonalizationGranted = gcmConsents[GoogleConsentType.adPersonalization]
?.consentStatus == ConsentStatus.granted;
// Initialize Google Mobile Ads SDK with consent
await MobileAds.instance.initialize();
// Set request configuration based on consent
final requestConfiguration = RequestConfiguration(
tagForChildDirectedTreatment: TagForChildDirectedTreatment.unspecified,
tagForUnderAgeOfConsent: TagForUnderAgeOfConsent.unspecified,
);
await MobileAds.instance.updateRequestConfiguration(requestConfiguration);
print('Google Ads initialized with consent');
} catch (e) {
print('Error initializing Google Ads: $e');
}
}
Complete Example #
Here's a complete example showing how to integrate Google Consent Mode into your Flutter app:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:securiti_consent_sdk/consent_sdk_plugin.dart';
import 'package:securiti_consent_sdk/cmp_sdk_options.dart';
import 'package:securiti_consent_sdk/models/google_consent_type.dart';
import 'package:securiti_consent_sdk/models/consent_status.dart';
class ConsentManager extends StatefulWidget {
@override
_ConsentManagerState createState() => _ConsentManagerState();
}
class _ConsentManagerState extends State<ConsentManager> {
final _consentSdkPlugin = ConsentSdkPlugin();
final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
static const EventChannel _eventChannel =
EventChannel('ai.securiti.consent_sdk_plugin/isSDKReady');
bool _sdkReady = false;
bool _consentsApplied = false;
@override
void initState() {
super.initState();
initializeConsentSDK();
}
void initializeConsentSDK() {
// Initialize SDK
CmpSDKOptions options = CmpSDKOptions(
appURL: 'YOUR_APP_URL',
cdnURL: 'YOUR_CDN_URL',
tenantID: 'YOUR_TENANT_ID',
appID: 'YOUR_APP_ID',
testingMode: false,
loggerLevel: CmpSDKLoggerLevel.info,
consentsCheckInterval: 3600,
languageCode: 'en',
locationCode: 'US',
);
_consentSdkPlugin.setupSDK(options.toMap());
// Listen for SDK ready
_eventChannel.receiveBroadcastStream().listen((event) async {
bool isReady = event as bool;
if (isReady) {
setState(() {
_sdkReady = isReady;
});
// Apply Google Consent Mode
await applyGoogleConsentMode();
// Show consent banner if needed
_consentSdkPlugin.presentConsentBanner();
}
});
}
Future<void> applyGoogleConsentMode() async {
try {
// Get GCM consents
Map<GoogleConsentType, Purpose> gcmConsents =
await _consentSdkPlugin.getGCMConsents();
// Log consent statuses
print('Google Consent Mode statuses:');
gcmConsents.forEach((type, purpose) {
print('${type.value}: ${purpose.consentStatus?.value}');
});
// Apply to Firebase Analytics
await _analytics.setConsent(
analyticsStorageConsentGranted:
gcmConsents[GoogleConsentType.analyticsStorage]?.consentStatus == ConsentStatus.granted,
adStorageConsentGranted:
gcmConsents[GoogleConsentType.adStorage]?.consentStatus == ConsentStatus.granted,
adUserDataConsentGranted:
gcmConsents[GoogleConsentType.adUserData]?.consentStatus == ConsentStatus.granted,
adPersonalizationConsentGranted:
gcmConsents[GoogleConsentType.adPersonalization]?.consentStatus == ConsentStatus.granted,
);
setState(() {
_consentsApplied = true;
});
print('Google Consent Mode applied successfully');
} catch (e) {
print('Error applying Google Consent Mode: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to apply consent settings')),
);
}
}
Future<void> refreshConsents() async {
if (!_sdkReady) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('SDK is not ready yet')),
);
return;
}
await applyGoogleConsentMode();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Consent settings refreshed')),
);
}
void showConsentBanner() {
if (!_sdkReady) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('SDK is not ready yet')),
);
return;
}
_consentSdkPlugin.presentConsentBanner();
}
void showPreferenceCenter() {
if (!_sdkReady) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('SDK is not ready yet')),
);
return;
}
_consentSdkPlugin.presentPreferenceCenter();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Consent Manager'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'SDK Status: ${_sdkReady ? "Ready" : "Initializing..."}',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
'Consents Applied: ${_consentsApplied ? "Yes" : "No"}',
style: TextStyle(fontSize: 16),
),
SizedBox(height: 24),
ElevatedButton(
onPressed: _sdkReady ? showConsentBanner : null,
child: Text('Show Consent Banner'),
),
SizedBox(height: 12),
ElevatedButton(
onPressed: _sdkReady ? showPreferenceCenter : null,
child: Text('Show Preference Center'),
),
SizedBox(height: 12),
ElevatedButton(
onPressed: _sdkReady ? refreshConsents : null,
child: Text('Refresh Google Consent Mode'),
),
],
),
),
);
}
}
Listening to Consent Changes #
You may want to refresh Google Consent Mode settings when users update their preferences:
import 'dart:async';
import 'package:securiti_consent_sdk/consent_sdk_plugin.dart';
import 'package:securiti_consent_sdk/models/google_consent_type.dart';
import 'package:securiti_consent_sdk/models/consent_status.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
class ConsentSyncService {
final _consentSdkPlugin = ConsentSdkPlugin();
final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
Timer? _syncTimer;
void startSyncing() {
// Sync consents every minute
_syncTimer = Timer.periodic(Duration(minutes: 1), (_) async {
await syncConsents();
});
}
void stopSyncing() {
_syncTimer?.cancel();
}
Future<void> syncConsents() async {
try {
Map<GoogleConsentType, Purpose> gcmConsents =
await _consentSdkPlugin.getGCMConsents();
await _analytics.setConsent(
analyticsStorageConsentGranted:
gcmConsents[GoogleConsentType.analyticsStorage]?.consentStatus == ConsentStatus.granted,
adStorageConsentGranted:
gcmConsents[GoogleConsentType.adStorage]?.consentStatus == ConsentStatus.granted,
adUserDataConsentGranted:
gcmConsents[GoogleConsentType.adUserData]?.consentStatus == ConsentStatus.granted,
adPersonalizationConsentGranted:
gcmConsents[GoogleConsentType.adPersonalization]?.consentStatus == ConsentStatus.granted,
);
print('Consents synced successfully');
} catch (e) {
print('Error syncing consents: $e');
}
}
}
Testing Google Consent Mode #
To verify your integration is working correctly:
- Enable Debug Logging:
CmpSDKOptions options = CmpSDKOptions(
// ... other options
loggerLevel: CmpSDKLoggerLevel.debug,
testingMode: true,
);
-
Check Console Output: Look for log messages showing the consent statuses being retrieved and applied.
-
Use Firebase DebugView:
- Enable debug mode in Firebase Analytics
- Check that consent signals are being sent correctly
- Verify events are being processed according to consent choices
- Verify Consent Updates:
Future<void> verifyConsents() async {
Map<GoogleConsentType, Purpose> gcmConsents =
await _consentSdkPlugin.getGCMConsents();
print('Current GCM Consents:');
gcmConsents.forEach((type, purpose) {
print(' ${type.value}: ${purpose.consentStatus?.value}');
});
}
Best Practices #
- Initialize Early: Call
setupSDK()as early as possible in your app lifecycle - Apply Before Tracking: Update Google Consent Mode before sending any analytics events
- Handle Errors: Always wrap consent calls in try-catch blocks
- Sync After Updates: Refresh consent signals after users update preferences
- Test Thoroughly: Test with different consent combinations to ensure proper behavior
- Check SDK Ready: Always verify the SDK is ready before calling
getGCMConsents()
Troubleshooting #
Issue: getGCMConsents() returns empty map
- Ensure SDK is initialized and ready
- Verify purpose-to-GCM mappings are configured in Securiti platform
- Check that purposes have been loaded successfully
Issue: Consent signals not applied to Google services
- Verify you're calling the correct Firebase/Google SDK consent methods
- Check that consent updates happen before any tracking calls
- Ensure proper integration with Firebase/Google Ads SDKs
Issue: Consent statuses not updating
- Call
getGCMConsents()after user makes consent changes - Verify the SDK is returning updated values
- Check for any errors in console logs
Issue: Type conversion errors
- Ensure you're properly accessing the Purpose object from the map
- Check that you're comparing ConsentStatus enum values correctly
- Verify the GoogleConsentType enum is being used properly
Additional Resources #
- Google Consent Mode Documentation
- Firebase Analytics Consent
- Google Mobile Ads Consent
- Flutter Firebase Documentation
IAB Europe TCF Integration #
TCF Overview #
The IAB Europe Transparency & Consent Framework (TCF) is the standard ad-tech vendors use to read a user's consent choices in the EU and EEA. Choices are encoded in a TC string and stored on the device under standard IABTCF_* keys. On Android these live in the app's default SharedPreferences, and on iOS in UserDefaults.standard. Third-party SDKs such as Google Mobile Ads read those keys directly.
The plugin gives you:
| Need | Method |
|---|---|
| Check whether TCF applies | isIabTcfEnabled() |
| Publisher configuration (disclosed purposes/vendors, UI texts) | getIabTcfConfig() |
| Vendor, purpose and stack details from IAB | getGlobalVendorList() |
| Purpose texts in another language | getIabPurposesTranslation(languageCode) |
| The stored TC string | getTCString() |
| The stored choices, decoded | getTCFConsents() |
| Save choices from a custom UI | setTCFChoices(choices) |
To enable TCF, turn on IAB Europe TCF for your mobile app in the Securiti platform and select the purposes, vendors and locations to disclose. Then publish the configuration.
Reading TCF Data #
Call the TCF methods after the SDK reports it is ready:
_eventChannel.receiveBroadcastStream().listen((event) async {
if (event != true) return;
if (!await _consentSdkPlugin.isIabTcfEnabled()) return;
final TCFConsents? consents = await _consentSdkPlugin.getTCFConsents();
if (consents == null) {
// No TC data stored yet: the user hasn't made a TCF choice
return;
}
if (consents.hasPurposeConsent(1) && consents.hasVendorConsent(755)) {
// Vendor 755 may store/access information on the device
}
});
To display vendor details, combine the configuration with the vendor list:
final config = await _consentSdkPlugin.getIabTcfConfig();
final gvl = await _consentSdkPlugin.getGlobalVendorList();
if (config != null && gvl != null) {
final disclosedVendors = (config.allowedVendorIds ?? [])
.map((id) => gvl.vendors[id])
.whereType<GVLVendor>()
.where((vendor) => !vendor.isDeleted); // deleted vendors must not be shown
for (final vendor in disclosedVendors) {
print('${vendor.name} - ${vendor.privacyPolicyUrl('en')}');
}
}
Building a Custom TCF UI #
If you render your own TCF screens, build a TCFChoices from the user's selections and save it with setTCFChoices(). The SDK encodes the TC string and the Google Additional Consent string, then writes the IABTCF_* keys.
Future<void> acceptAllTcf() async {
final config = await _consentSdkPlugin.getIabTcfConfig();
if (config == null) return; // TCF not enabled (or not applicable here)
final allowedPurposes = (config.allowedPurposeIds ?? []).toSet();
final choices = TCFChoices(
purposeConsents:
(config.purposeConsents ?? []).toSet().intersection(allowedPurposes),
purposeLegitimateInterests:
(config.purposeLegitimateInterests ?? []).toSet().intersection(allowedPurposes),
specialFeatureOptIns: (config.allowedSpecialFeatureIds ?? []).toSet(),
vendorConsents: (config.allowedVendorIds ?? []).toSet(),
vendorLegitimateInterests: (config.allowedVendorIds ?? []).toSet(),
googleAtpConsents: (config.allowedGoogleAtpIds ?? []).toSet(),
);
final tcString = await _consentSdkPlugin.setTCFChoices(choices);
print('Saved TC string: $tcString');
}
Future<void> rejectAllTcf() async {
await _consentSdkPlugin.setTCFChoices(const TCFChoices());
}
To pre-fill a custom UI with the user's current selections, use TCFConsents.choices:
final current = (await _consentSdkPlugin.getTCFConsents())?.choices ?? const TCFChoices();
Notes:
purposeLegitimateInterestsandvendorLegitimateInterestslist the items the user has not objected to. Leave an ID out to record an objection.googleAtpConsentsholds Google Ad Tech Provider IDs, which are not IAB vendor IDs. They are signalled in the Additional Consent string (IABTCF_AddtlConsent).setTCFChoices()only stores the choices on the device. It does not upload anything.
Platform Differences #
| Behavior | Android | iOS |
|---|---|---|
isIabTcfEnabled() / getIabTcfConfig() |
Also false/null when the user's location is outside the configured TCF locations |
Reflects the published configuration only |
getIabPurposesTranslation('en') |
Passed to the native SDK | Returns null; use getGlobalVendorList() for English texts |
TCFConsents.vendorListVersion, consentLanguage, created, lastUpdated, disclosedVendors, disclosedGoogleAtps |
Always null |
Decoded from the TC string |
IabTcfConfig.enableGcmIntegration |
Supported | Not used |
GVLPurpose.descriptionLegal, GVLVendor.cookieRefresh, isAtp, policyUrl |
Populated when present | Not populated |
GVLVendor.deletedDate |
Not populated | Populated |
TCF Troubleshooting #
isIabTcfEnabled() returns false or getIabTcfConfig() returns null:
- Make sure IAB Europe TCF is enabled and published for the app in the Securiti platform.
- On Android, check that the
locationCodepassed toCmpSDKOptionsis one of the configured TCF locations, or that TCF is configured for all locations. - Make sure the SDK is ready before you call these methods.
setTCFChoices() returns null:
- TCF isn't configured, or the Global Vendor List couldn't be downloaded. Check network access and try
getGlobalVendorList(forceRefresh: true).
getTCFConsents() returns null:
- The user hasn't made a TCF choice yet, so no TC string is stored on the device.
TCF Resources #
- IAB Europe TCF
- TCF technical specifications (TC string,
IABTCF_*keys) - Google Additional Consent mode
Data Models #
ConsentStatus Enum #
Represents the consent status for a purpose or permission:
enum ConsentStatus {
granted, // User has granted consent
declined, // User has declined consent
notDetermined, // Consent has not been determined yet
withdrawn // User has withdrawn consent
}
GoogleConsentType Enum #
Represents the Google Consent Mode consent types:
enum GoogleConsentType {
analyticsStorage, // analytics_storage
adStorage, // ad_storage
adUserData, // ad_user_data
adPersonalization // ad_personalization
}
GcmConfig #
Represents the Google Consent Mode configuration:
class GcmConfig {
final bool? showGcmDescription;
final Map<String, String>? gcmDescription;
final DefaultMapping? defaultMapping;
final Map<String, DefaultMapping>? regionOverrides;
}
Properties:
showGcmDescription: Whether to display GCM description to usersgcmDescription: Localized descriptions (language code → description text)defaultMapping: Default purpose-to-consent-type mappingsregionOverrides: Region-specific mapping overrides (region code → mapping)
DefaultMapping #
Represents purpose ID mappings to Google Consent Mode types:
class DefaultMapping {
final List<int>? analyticsStorage;
final List<int>? adStorage;
final List<int>? adUserData;
final List<int>? adPersonalization;
}
Properties:
analyticsStorage: Purpose IDs for analytics storage consentadStorage: Purpose IDs for ad storage consentadUserData: Purpose IDs for ad user data consentadPersonalization: Purpose IDs for ad personalization consent
Purpose #
Represents a consent purpose:
class Purpose {
final int? purposeId;
final Map<String, String>? purposeName;
final Map<String, String>? purposeDescription;
final List<SDK>? sdks;
final ConsentStatus? consentStatus;
final bool? disableOptOut;
final Map<String, String>? optOutText;
final bool? hideDetails;
final bool isGADMapped;
final Map<String, String> gadDescription;
}
AppPermission #
Represents an app permission:
class AppPermission {
final int? id;
final String? name;
final String? permissionId;
final Map<String, String>? description;
final String? group;
final int? groupId;
final ConsentStatus? consentStatus;
final Map<String, String>? nameMap;
final bool? isSettingsPromptEnabled;
}
CmpSDKOptions #
Configuration options for initializing the SDK:
class CmpSDKOptions {
final String appURL;
final String cdnURL;
final String tenantID;
final String appID;
final bool testingMode;
final CmpSDKLoggerLevel loggerLevel;
final int consentsCheckInterval;
final String? subjectId;
final String? languageCode;
final String? locationCode;
}
BannerConfig #
Configuration for the consent banner:
class BannerConfig {
final bool? hideCloseButton;
final bool? hideAcceptButton;
final bool? embedDSRPortalLink;
final bool? recordConsentUponAppStart;
final bool? hideToggleForEssentialCategories;
final String? name;
final String? dsrPortalLink;
final String? complianceType;
final String? bannerReappearanceTime;
final String? privacyNoticeLink;
final Map<String, String>? accept;
final Map<String, String>? reject;
final Map<String, String>? bannerText;
final Map<String, String>? bannerHeading;
final String? bannerPosition;
final String? buttonShape;
final CustomColors? customPaletteTheme;
// ... and more
}
IabTcfConfig #
The publisher's IAB Europe TCF configuration from the Securiti CDN (models/iab_tcf_config.dart). Every field is optional, and a field missing from the CDN is null.
class IabTcfConfig {
// Disclosed IDs
final List<int>? allowedVendorIds;
final List<int>? allowedPurposeIds;
final List<int>? allowedSpecialPurposeIds;
final List<int>? allowedFeatureIds;
final List<int>? allowedSpecialFeatureIds;
final List<int>? allowedStackIds;
final List<int>? allowedDataCategoryIds;
final List<int>? allowedGoogleAtpIds; // Google Ad Tech Providers (Additional Consent)
final int? gvlVersion;
// Legal bases
final List<int>? purposeConsents; // purposes processed on consent
final List<int>? purposeLegitimateInterests; // purposes processed on legitimate interest
// Localized UI texts (language code → text)
final Map<String, String>? bannerText;
final Map<String, String>? vendorListHeading;
final Map<String, String>? vendorListDescription;
final Map<String, String>? iabPurposeHeading;
final Map<String, String>? iabPurposeDescription;
final Map<String, String>? acceptAllButtonText;
final Map<String, String>? rejectAllButtonText;
final Map<String, String>? advancedSettingsText;
final bool? isTCStorageDescriptionEnabled;
final Map<String, String>? tcStorageDescription;
final Map<String, String>? iabVendorSubtabDescription;
final bool? showIabVendorSubtabDescription;
final bool? isGoogleAtpEnabled;
final Map<String, String>? googleAtpSubtabDescription;
final bool? showGoogleAtpSubtabDescription;
// Applicability
final bool? allLocations; // true: TCF applies everywhere
final List<String>? locations; // location codes, used when allLocations is false
final bool? enableGcmIntegration; // Android only
}
GlobalVendorList #
The IAB Global Vendor List (GVL v3) with Google's Ad Tech Provider list merged in (models/global_vendor_list.dart). Sections are keyed by numeric ID. Malformed entries are dropped rather than failing the whole list.
class GlobalVendorList {
final int? gvlSpecificationVersion;
final int? vendorListVersion;
final int? tcfPolicyVersion;
final String? lastUpdated;
final Map<int, GVLPurpose> purposes;
final Map<int, GVLPurpose> specialPurposes;
final Map<int, GVLPurpose> features;
final Map<int, GVLPurpose> specialFeatures;
final Map<int, GVLStack> stacks;
final Map<int, GVLDataCategory> dataCategories;
final Map<int, GVLVendor> vendors;
final int? googleAtpVersion;
final List<GVLGoogleAtpProvider> googleAcOnlyProviders; // Google ATPs that aren't IAB vendors
}
Related types:
GVLPurpose:id,name,description,illustrations, anddescriptionLegal(Android only). It is used for purposes, special purposes, features and special features.GVLStack:id,name,description,purposes,specialFeatures.GVLDataCategory:id,name,description.GVLVendor:id,name,purposes,legIntPurposes,flexiblePurposes,specialPurposes,features,specialFeatures,dataDeclaration,cookieMaxAgeSeconds,usesCookies,usesNonCookieAccess,deviceStorageDisclosureUrl,dataRetention,urls, plus platform-specific fields (see Platform Differences). Helpers:isDeleted: the vendor was deleted by IAB and must not be disclosed or receive signals.privacyPolicyUrl(language)andlegitimateInterestClaimUrl(language): return the URL for the language, falling back to English and then to the first entry.
GVLDataRetention:stdRetention(days), plus per-purposepurposesandspecialPurposesoverrides.GVLVendorUrl:langId,privacy,legIntClaim.GVLGoogleAtpProvider:id,name,policyUrl.
TCFChoices #
A user's TCF choices, passed to setTCFChoices() (models/tcf_consents.dart). Every set defaults to empty.
class TCFChoices {
final Set<int> purposeConsents;
final Set<int> purposeLegitimateInterests; // purposes NOT objected to
final Set<int> specialFeatureOptIns;
final Set<int> vendorConsents;
final Set<int> vendorLegitimateInterests; // vendors NOT objected to
final Set<int> googleAtpConsents; // Google ATP IDs (Additional Consent)
}
TCFConsents #
The TC data stored on the device, returned by getTCFConsents() (models/tcf_consents.dart).
class TCFConsents {
final String tcString; // IABTCF_TCString
final bool? gdprApplies; // null when not determined
final Set<int> purposeConsents;
final Set<int> purposeLegitimateInterests;
final Set<int> specialFeatureOptIns;
final Set<int> vendorConsents;
final Set<int> vendorLegitimateInterests;
final Set<int> googleAtpConsents;
final String? additionalConsent; // IABTCF_AddtlConsent
final int? cmpId;
final int? cmpVersion;
final int? policyVersion;
// iOS only (null on Android)
final int? vendorListVersion;
final String? consentLanguage;
final DateTime? created; // UTC
final DateTime? lastUpdated; // UTC
final Set<int>? disclosedVendors;
final Set<int>? disclosedGoogleAtps;
}
Helpers: hasPurposeConsent(id), hasVendorConsent(id), hasVendorLegitimateInterest(id), and choices, which returns the stored selections as a TCFChoices for pre-filling a custom UI.
Example App #
A complete example app is included in the example folder. To run it:
cd example
flutter run
The example app demonstrates:
- SDK initialization
- Presenting consent banner and preference center
- Getting and setting consents
- Retrieving purposes and permissions
- Google Consent Mode integration with Firebase
- IAB Europe TCF: reading the TCF config, vendor list, translations and stored TC data, and saving accept-all / reject-all choices with
setTCFChoices()
License #
This project is licensed under the terms specified by Securiti.
Support #
For support, please contact Securiti support or visit the Securiti documentation portal.