Flutter集成CMP SDK插件cmp_sdk的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter集成CMP SDK插件cmp_sdk的使用

cmp_sdk 是一个用于在Flutter应用程序中集成和管理同意管理平台(CMP)功能的插件。该插件提供了一种简单而有效的方式来处理用户对数据收集和使用的同意,以符合GDPR等隐私法律。

特性

  • 使用自定义配置初始化CMP。
  • 可配置呈现样式的打开同意层UI。
  • 检查和管理用户的供应商和目的同意情况。
  • 导入/导出CMP配置字符串。
  • 完全支持自定义回调和同意状态检查。

安装

要在项目中使用cmp_sdk插件,请将其添加到pubspec.yaml文件中:

dependencies:
  cmp_sdk: ^x.x.x

然后运行以下命令安装插件:

flutter pub get

快速开始

创建带有基本配置的CmpSdk实例:

import 'package:cmp_sdk/cmp_sdk.dart';
import 'package:cmp_sdk/cmp_config.dart';

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

  // 使用基本配置初始化CMP SDK
  final cmpSdk = CmpSdk.createInstance(
    id: "your_cmp_id",
    domain: "your_cmp_domain",
    appName: "your_app_name",
    language: "your_preferred_language",
  );
}

示例用法

下面是一个如何在应用中使用cmp_sdk来配置同意层并处理用户同意的示例:

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late CmpSdk cmpSdk;

  [@override](/user/override)
  void initState() {
    super.initState();
    initCmpSdk();
  }

  Future<void> initCmpSdk() async {
    // 创建带有自定义配置的CMP SDK实例
    final cmpConfig = CmpConfig(
      id: "your_cmp_id",
      domain: "your_cmp_domain",
      appName: "your_app_name",
      language: "your_preferred_language",
      screenConfig: ScreenConfig.halfScreenBottom, // 设置层屏幕
      iosPresentationStyle: IosPresentationStyle.popover,
      androidPresentationStyle: AndroidPresentationStyle.dialog,
      isDebugMode: true,
    );
    cmpSdk = CmpSdk.createInstanceWithConfig(cmpConfig);

    // 初始化CMP SDK并执行必要的设置
    await cmpSdk.initialize();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('CMP SDK Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 打开同意层供用户给予同意
              await cmpSdk.openConsentLayer();
            },
            child: Text('Open Consent Layer'),
          ),
        ),
      ),
    );
  }
}

此示例展示了如何使用自定义配置初始化CmpSdk,配置同意层的UI,并打开同意层供用户交互。

更详细的示例Demo

以下是一个更完整的示例,展示了如何使用cmp_sdk插件进行更多的操作,如导入CMP字符串、检查同意要求、启用/禁用供应商和目的等。

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 'package:fluttertoast/fluttertoast.dart';
import 'package:cmp_sdk/cmp_sdk.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/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](/user/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 resetConsent() async {
    await _cmpSdkPlugin.reset();
    Fluttertoast.showToast(msg: 'Reset consent data');
  }

  void getStatus() async {
    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 = '';
      });
    }
  }

  [@override](/user/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('Reset', resetConsent),
        _buildActionButton('acceptAll', acceptAll),
        _buildActionButton('rejectAll', rejectAll),
        _buildActionButton('disableVendors', disableVendors),
        _buildActionButton('enable Vendors', enableVendors),
        _buildActionButton('enable Purposes', enablePurposes),
        _buildActionButton('disable Purposes', disablePurposes),
      ],
    );
  }

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

更多关于Flutter集成CMP SDK插件cmp_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter集成CMP SDK插件cmp_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter项目中集成CMP(Compliance Management Platform,合规管理平台)SDK插件cmp_sdk时,通常你需要按照以下步骤进行操作。以下是一个基本的集成和使用示例,包括如何在Flutter项目中配置和使用CMP SDK插件。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加cmp_sdk插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  cmp_sdk: ^x.y.z  # 请替换为实际的版本号

2. 获取并导入CMP SDK

确保你已经从CMP SDK的提供者那里获取了正确的SDK包,并且已经将其放置在项目的合适位置(例如ios/android/目录下)。

3. 配置iOS项目

3.1 在ios/Podfile中添加CMP SDK的Pod依赖(如果适用)

platform :ios, '10.0'

target 'Runner' do
  use_frameworks!
  config = use_native_modules!

  # Flutter Pod
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))

  # Add CMP SDK Pod dependency here
  pod 'CMP_iOS_SDK', '~> x.y.z'  # 请替换为实际的版本号和Pod名称
end

3.2 在Info.plist中添加必要的配置

根据CMP SDK的要求,你可能需要在Info.plist中添加一些必要的配置,比如隐私政策URL等。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
<key>CMP_PRIVACY_POLICY_URL</key>
<string>https://your-privacy-policy-url.com</string>

4. 配置Android项目

4.1 在android/app/build.gradle中添加CMP SDK的依赖

dependencies {
    implementation project(':flutter')
    implementation 'com.android.support:multidex:1.0.3'
    // Add CMP SDK dependency here
    implementation 'com.cmp.sdk:android:x.y.z'  # 请替换为实际的版本号和依赖名称
}

4.2 在AndroidManifest.xml中添加必要的权限和配置

根据CMP SDK的要求,你可能需要在AndroidManifest.xml中添加一些必要的权限和配置。

<uses-permission android:name="android.permission.INTERNET" />
<application
    ... >
    <meta-data
        android:name="com.cmp.sdk.config"
        android:value="your_config_value" />
    ...
</application>

5. 在Flutter代码中使用CMP SDK

创建一个新的Dart文件(例如cmp_service.dart),并在其中编写CMP SDK的初始化和使用代码。

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

class CmpService {
  static const MethodChannel _channel = MethodChannel('cmp_sdk');

  static Future<void> initialize() async {
    try {
      // 初始化CMP SDK,传递必要的配置
      await _channel.invokeMethod('initialize', {
        'configKey1': 'configValue1',
        'configKey2': 'configValue2',
      });
    } on PlatformException catch (e) {
      print("Failed to initialize CMP SDK: '${e.message}'.");
    }
  }

  static Future<bool> checkCompliance() async {
    try {
      final bool isCompliant = await _channel.invokeMethod('checkCompliance');
      return isCompliant;
    } on PlatformException catch (e) {
      print("Failed to check compliance: '${e.message}'.");
      return false;
    }
  }

  // 添加其他CMP SDK方法的封装
}

6. 在主应用中使用CMP Service

在你的主应用代码(例如main.dart)中调用CMP Service。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('CMP SDK Integration'),
        ),
        body: FutureBuilder<void>(
          future: CmpService.initialize(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Center(
                child: ElevatedButton(
                  onPressed: async () {
                    final bool isCompliant = await CmpService.checkCompliance();
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text(isCompliant ? 'Compliant' : 'Not Compliant'),
                      ),
                    );
                  },
                  child: Text('Check Compliance'),
                ),
              );
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

总结

以上示例展示了如何在Flutter项目中集成CMP SDK插件cmp_sdk,并通过Dart代码调用CMP SDK的方法。请根据你的实际CMP SDK文档和需求调整配置和代码。

回到顶部