securiti_consent_sdk 1.142.0-4rc copy "securiti_consent_sdk: ^1.142.0-4rc" to clipboard
securiti_consent_sdk: ^1.142.0-4rc 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 #

  1. Installation
  2. Setup
  3. Updating Dependencies
  4. Basic Usage
  5. API Reference
  6. Google Consent Mode Integration
  7. Data Models
  8. 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 #

  1. Add the Securiti Maven repository to your android/app/build.gradle:
repositories {
    google()
    mavenCentral()
    maven {
        url 'https://cdn-prod.securiti.ai/consent/maven'
    }
}
  1. Ensure your MainActivity extends FlutterFragmentActivity:
import io.flutter.embedding.android.FlutterFragmentActivity

class MainActivity: FlutterFragmentActivity() {
}
  1. Minimum Requirements:

    • Android API Level 24+ (Android 7.0)
    • Kotlin 1.9.22+
    • Gradle 8.2.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

iOS Setup #

  1. Run pod install in your iOS folder:
cd ios
pod install
  1. Ensure your iOS deployment target is set to 15.0 or higher in ios/Podfile:
platform :ios, '15.0'
  1. Minimum Requirements:

    • iOS 15.0+
    • Swift 5.0+
    • Xcode 14.0+
  2. Key Dependencies (automatically included by the plugin):

    • Securiti ConsentUI: 1.1.141.0 (includes Google Consent Mode support)
  3. For Firebase Analytics integration, add to your Podfile:

# Firebase Analytics (required for Google Consent Mode)
pod 'Firebase/Analytics'
  1. For Google Mobile Ads integration, add to your Podfile:
# Google Mobile Ads (required for AdMob with Consent Mode)
pod 'Google-Mobile-Ads-SDK'

Updating Dependencies #

Updating to Latest Version #

To update the Securiti Consent SDK to the latest version:

  1. Update pubspec.yaml:
dependencies:
  securiti_consent_sdk: ^1.141.0  # Update to latest version
  1. 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
    }
}
  1. For iOS - Manual Update (if needed):

Update the version in your ios/Podfile:

# Override Securiti Consent SDK version
pod 'ConsentUI', '1.1.141.0'

Then run:

cd ios
pod update ConsentUI

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 (Podfile):

# Firebase Analytics
pod 'Firebase/Analytics', '~> 10.18.0'

# Google Mobile Ads (if using AdMob)
pod 'Google-Mobile-Ads-SDK', '~> 10.14.0'

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();
    }
  });
}
// 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 (use CmpSDKOptions.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();

getConsent(dynamic identifier)

Gets the consent status for a specific purpose or permission.

Parameters:

  • identifier: Either an int (purpose ID) or String (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 a Purpose or AppPermission object
  • status: 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);

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/storage
  • GoogleConsentType.adStorage - Controls consent for advertising cookies/storage
  • GoogleConsentType.adUserData - Controls consent for sending user data to Google
  • GoogleConsentType.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


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:

  1. analytics_storage - Permission to store analytics data
  2. ad_storage - Permission to store advertising data
  3. ad_user_data - Permission to send user data to Google for advertising
  4. 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 #

  1. Configure purpose-to-Google-consent-type mappings in your Securiti platform
  2. Initialize the SDK in your Flutter app
  3. Call getGCMConsents() to retrieve mapped consent statuses
  4. 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:

  1. Navigate to your mobile app configuration
  2. Go to the Purposes section
  3. For each purpose, configure the Google Consent Mode mapping
  4. 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'),
            ),
          ],
        ),
      ),
    );
  }
}

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');
    }
  }
}

To verify your integration is working correctly:

  1. Enable Debug Logging:
CmpSDKOptions options = CmpSDKOptions(
  // ... other options
  loggerLevel: CmpSDKLoggerLevel.debug,
  testingMode: true,
);
  1. Check Console Output: Look for log messages showing the consent statuses being retrieved and applied.

  2. 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
  1. 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 #

  1. Initialize Early: Call setupSDK() as early as possible in your app lifecycle
  2. Apply Before Tracking: Update Google Consent Mode before sending any analytics events
  3. Handle Errors: Always wrap consent calls in try-catch blocks
  4. Sync After Updates: Refresh consent signals after users update preferences
  5. Test Thoroughly: Test with different consent combinations to ensure proper behavior
  6. 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 #


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 users
  • gcmDescription: Localized descriptions (language code → description text)
  • defaultMapping: Default purpose-to-consent-type mappings
  • regionOverrides: 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 consent
  • adStorage: Purpose IDs for ad storage consent
  • adUserData: Purpose IDs for ad user data consent
  • adPersonalization: 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
}

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

License #

This project is licensed under the terms specified by Securiti.

Support #

For support, please contact Securiti support or visit the Securiti documentation portal.

1
likes
145
points
878
downloads

Publisher

verified publishersecuriti.ai

Weekly Downloads

A Flutter plugin for managing user consent preferences and compliance with privacy regulations. Integrates with Securiti's Consent Management Platform.

Repository
View/report issues

Documentation

Documentation
API reference

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on securiti_consent_sdk

Packages that implement securiti_consent_sdk