cmp_sdk 2.5.3 copy "cmp_sdk: ^2.5.3" to clipboard
cmp_sdk: ^2.5.3 copied to clipboard

The CMP Plugin allows you to integrate Consent Management functionality.

example/lib/main.dart

import 'package:cmp_sdk/cmp_config.dart';
import 'package:cmp_sdk/cmp_ui_config.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:cmp_sdk/cmp_sdk.dart';
import 'package:fluttertoast/fluttertoast.dart';

void main() {
  runApp(const MyApp());
}

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

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

const String _cmpId = "b43fcc03b1a67";
const String _cmpDomain = "delivery.consentmanager.net";
const String _cmpAppName = "Test";
const String _cmpLanguage = "de";

class _MyAppState extends State<MyApp> {
  String _consentStatus = '';
  String _callbackLogs = '';
  String _cmpString = '';
  String _idString = '1';
  ScreenConfig _selectedScreenConfig = ScreenConfig.fullScreen;

  final CmpConfig _cmpConfig = CmpConfig(
      id: _cmpId,
      domain: _cmpDomain,
      appName: _cmpAppName,
      language: _cmpLanguage,
      timeout: 8000,
      screenConfig: ScreenConfig.halfScreenBottom,
      isAutomaticATTRequest: true,
      iosPresentationStyle: IosPresentationStyle.pagesheet,
      androidPresentationStyle: AndroidPresentationStyle.dialog);

  late CmpSdk _cmpSdkPlugin;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initCmp();
    });
  }

  void _updateCmpUiConfig(ScreenConfig screenConfig) async {
    await _cmpSdkPlugin.configureConsentLayer(config: screenConfig);
  }

  Future<void> initCmp() async {
    try {
      _cmpSdkPlugin = CmpSdk.createInstanceWithConfig(_cmpConfig);
      await _cmpSdkPlugin.initialize();
      setEventCallbacks();
    } on PlatformException {
      if (kDebugMode) {
        print("platform not supported");
      }
    }

    if (!mounted) return;
  }

  void acceptAll() async {
    await _cmpSdkPlugin.acceptAll();
    Fluttertoast.showToast(msg: 'accepted Consent by acceptAll API');
  }

  void rejectAll() async {
    await _cmpSdkPlugin.rejectAll();
    Fluttertoast.showToast(msg: 'rejected Consent by rejectAll API');
  }

  void openConsentLayer() async {
    await _cmpSdkPlugin.openConsentLayer();
  }

  void disableVendors() async {
    if (_idString.isEmpty) {
      Fluttertoast.showToast(msg: 'ID is empty');
      return;
    }
    await _cmpSdkPlugin.disableVendors([_idString]);
    Fluttertoast.showToast(msg: 'disabled Vendor');
  }

  void enableVendors() async {
    if (_idString.isEmpty) {
      Fluttertoast.showToast(msg: 'ID is empty');
      return;
    }
    await _cmpSdkPlugin.enableVendors([_idString]);
    Fluttertoast.showToast(msg: 'enabled Vendor');
  }

  void disablePurposes() async {
    if (_idString.isEmpty) {
      Fluttertoast.showToast(msg: 'ID is empty');
      return;
    }
    await _cmpSdkPlugin.disablePurposes([_idString]);
    Fluttertoast.showToast(msg: 'disabled Purpose');
  }

  void enablePurposes() async {
    if (_idString.isEmpty) {
      Fluttertoast.showToast(msg: 'ID is empty');
      return;
    }
    await _cmpSdkPlugin.enablePurposes([_idString]);
    Fluttertoast.showToast(msg: 'enabled Purpose');
  }

  void openConsentLayerOnCheck() async {
    await _cmpSdkPlugin.openConsentLayerOnCheck();
  }

  void resetConsent() async {
    await _cmpSdkPlugin.reset();
    Fluttertoast.showToast(msg: 'Reset consent data');
    // Add any additional logic after resetting consent
  }

  void getStatus() async {
    // Define a helper function to fetch status with a given name and method
    Future<String> fetchStatus(
        String name, Future<dynamic> Function() method) async {
      try {
        final result = await method();
        return '$name: ${result.toString()}';
      } catch (err) {
        if (kDebugMode) {
          print(err);
        }
        return '$name: Error';
      }
    }

    // List of all status fetch operations
    final statusFutures = [
      fetchStatus('Export CmpString', _cmpSdkPlugin.exportCmpString),
      fetchStatus('Has Consent', _cmpSdkPlugin.hasConsent),
      fetchStatus(
          'consent Requested Today', _cmpSdkPlugin.consentRequestedToday),
      fetchStatus('All Vendors', _cmpSdkPlugin.getAllVendors),
      fetchStatus('All Purposes', _cmpSdkPlugin.getAllPurposes),
      fetchStatus('Enabled Vendors', _cmpSdkPlugin.getEnabledVendors),
      fetchStatus('Enabled Purposes', _cmpSdkPlugin.getEnabledPurposes),
      fetchStatus('Disabled Vendors', _cmpSdkPlugin.getDisabledVendors),
      fetchStatus('Disabled Purposes', _cmpSdkPlugin.getDisabledPurposes),
      fetchStatus('US Privacy String', _cmpSdkPlugin.getUSPrivacyString),
      fetchStatus('Google AC String', _cmpSdkPlugin.getGoogleACString),
    ];

    final List<String> statusReports = await Future.wait(statusFutures);

    final String statusString = statusReports.join('\n');

    setState(() {
      _consentStatus = statusString;
    });
  }

  Future<String> fetchStatus(
      String name, Future<dynamic> Function() method) async {
    try {
      final result = await method();
      return '$name: ${result.toString()}';
    } catch (err) {
      if (kDebugMode) {
        print('Error fetching $name: $err');
      }
      return '$name: Error - ${err.toString()}';
    }
  }

  void setEventCallbacks() {
    _cmpSdkPlugin.setCallbacks(onOpen: () {
      logCallback('Consent layer opened');
    }, onClose: () {
      logCallback('Consent layer closed');
    }, onNotOpened: () {
      logCallback('Consent layer not opened');
    }, onError: (type, message) {
      logCallback('Error: $type - $message');
    }, onButtonClicked: (buttonType) {
      logCallback('Button clicked: $buttonType');
    }, onGoogleConsentUpdated: (consentMap) {
      logCallback('Google consent updated:  ${consentMap.toString()}');
    });
  }

  void logCallback(String message) {
    if (kDebugMode) {
      print('Logging callback: $message');
    }
    setState(() {
      _callbackLogs += "$message\n";
    });
  }

  Future<void> importCmpString() async {
    if (_cmpString.isEmpty) {
      Fluttertoast.showToast(msg: 'CMP String is empty');
      return;
    }
    final success = await _cmpSdkPlugin.importCmpString(_cmpString);
    Fluttertoast.showToast(
        msg: success ? 'Import successful' : 'Import failed');
    if (success) {
      setState(() {
        _cmpString = '';
      });
    }
  }

  Future<void> checkConsentIsRequired() async {
    final isConsentRequired = await _cmpSdkPlugin.check();
    Fluttertoast.showToast(
        msg: isConsentRequired
            ? 'Consent is required'
            : 'Consent is not required');
  }

  Future<void> checkVendorConsent() async {
    if (_idString.isEmpty) {
      Fluttertoast.showToast(msg: 'Vendor ID is empty');
      return;
    }
    final hasConsent = await _cmpSdkPlugin.hasVendor(_idString);
    Fluttertoast.showToast(
        msg: hasConsent
            ? 'Consent for vendor exists $_idString'
            : 'No consent for vendor: $_idString');
  }

  Future<void> checkPurposeConsent() async {
    if (_idString.isEmpty) {
      Fluttertoast.showToast(msg: 'Purpose ID is empty');
      return;
    }
    final hasConsent = await _cmpSdkPlugin.hasPurpose(_idString);
    Fluttertoast.showToast(
        msg: hasConsent
            ? 'Consent for purpose exists $_idString'
            : 'No consent for purpose: $_idString');
  }

  Future<void> requestATTPermission() async {
    await _cmpSdkPlugin.requestATTPermission();
  }

  Future<void> getLastATTRequestDate() async {
    final lastRequest = await _cmpSdkPlugin.getLastATTRequestDate();
    Fluttertoast.showToast(msg: 'last Att request Date: $lastRequest');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('CMP SDK Example App'),
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildConfigurationSection(),
              const SizedBox(height: 24.0),
              _buildActionButtons(),
              const SizedBox(height: 24.0),
              _buildStatusSection(),
              const SizedBox(height: 24.0),
              _buildLogsSection(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildConfigurationSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextFormField(
              decoration:
                  const InputDecoration(labelText: 'Enter CMP import string'),
              onChanged: (value) => setState(() => _cmpString = value),
            ),
            const SizedBox(height: 12.0),
            TextFormField(
              decoration:
                  const InputDecoration(labelText: 'Enter Purpose/Vendor ID'),
              onChanged: (value) => setState(() => _idString = value),
            ),
            const SizedBox(height: 12.0),
            _buildScreenConfigDropdown(), // Add the dropdown here
          ],
        ),
      ),
    );
  }

  Widget _buildScreenConfigDropdown() {
    return DropdownButton<ScreenConfig>(
      value: _selectedScreenConfig,
      icon: const Icon(Icons.arrow_downward),
      elevation: 16,
      style: const TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (ScreenConfig? newValue) {
        setState(() {
          _selectedScreenConfig = newValue!;
          _updateCmpUiConfig(_selectedScreenConfig);
        });
      },
      items: ScreenConfig.values
          .map<DropdownMenuItem<ScreenConfig>>((ScreenConfig value) {
        return DropdownMenuItem<ScreenConfig>(
          value: value,
          child: Text(value.name),
        );
      }).toList(),
    );
  }

  Widget _buildActionButtons() {
    return Wrap(
      spacing: 10.0,
      children: [
        _buildActionButton('Check Vendor Consent', checkVendorConsent),
        _buildActionButton('Check Purpose Consent', checkPurposeConsent),
        _buildActionButton('Import CMP String', importCmpString),
        _buildActionButton('Check Consent Requirement', checkConsentIsRequired),
        _buildActionButton('Open Consent', openConsentLayer),
        _buildActionButton('Get Status', getStatus),
        _buildActionButton('Open Layer on Check', openConsentLayerOnCheck),
        _buildActionButton('Reset', resetConsent),
        _buildActionButton('acceptAll', acceptAll),
        _buildActionButton('rejectAll', rejectAll),
        _buildActionButton('disableVendors', disableVendors),
        _buildActionButton('enable Vendors', enableVendors),
        _buildActionButton('enable Purposes', enablePurposes),
        _buildActionButton('disable Purposes', disablePurposes),
        _buildActionButton('request ATT', requestATTPermission),
        _buildActionButton('last request Date ATT', getLastATTRequestDate),
      ],
    );
  }

  Widget _buildActionButton(String label, VoidCallback onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(label),
    );
  }

  Widget _buildStatusSection() {
    return Card(
      child: ListTile(
        title: const Text('Consent Status'),
        subtitle: Text(
            _consentStatus.isEmpty ? 'No status available' : _consentStatus),
      ),
    );
  }

  Widget _buildLogsSection() {
    return Card(
      child: ListTile(
        title: const Text('Callback Logs'),
        subtitle: Text(_callbackLogs.isEmpty ? 'No logs' : _callbackLogs),
      ),
    );
  }
}
2
likes
160
points
616
downloads

Publisher

verified publisherbentech.app

Weekly Downloads

The CMP Plugin allows you to integrate Consent Management functionality.

Homepage

Documentation

API reference

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on cmp_sdk