Skip to main content

go_trust_mobile_sdk 1.0.9 copy "go_trust_mobile_sdk: ^1.0.9" to clipboard
go_trust_mobile_sdk: ^1.0.9 copied to clipboard

A Flutter mobile SDK for GoTrust consent and preference management.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:go_trust_mobile_sdk/features/consent_form/services/go_trust_sdk_helper.dart';
import 'package:go_trust_mobile_sdk/features/consent_form/consent_form_page.dart';
import 'package:go_trust_mobile_sdk/features/consent_preferences/widgets/login_page.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'GoTrust SDK Sample',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
        useMaterial3: true,
      ),
      home: const GoTrustSamplePage(),
    );
  }
}

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

  @override
  State<GoTrustSamplePage> createState() => _GoTrustSamplePageState();
}

class _GoTrustSamplePageState extends State<GoTrustSamplePage> {
  static const String _baseUrl = 'YOUR_BASE_URL';

  static const String _sourceId =
      'YOUR_SOURCE_ID';
  static const String _customerId =
      'YOUR_CUSTOMER_ID';
  static const String _preferenceFormId =
      'YOUR_PF_FORM_ID';
  static const String _pfToken = "YOUR_PF_TOKEN";
  static const String _consentUserToken = "USER_SPECIFIC_CONSENT_FORM_TOKEN";
  static const String _pfUserToken = "USER_SPECIFIC_PREFERENCE_CENTER_TOKEN";
  static const Map<String, dynamic> _subjectIdentityValues = {
    "YOUR_FIELD_ID": "YOUR_FIELD_VALUE",
  };


  static const Map<String, dynamic> _additionalParams = {
    'YOUR_FIELD_ID': 'YOUR_FIELD_VALUE',
  };

  Future<bool?> _shouldOpenConsentForm(
      Map<String, dynamic> subjectIdentityValues) async {
    return GoTrustSdkHelper.showConsentForm(
   sourceId:    _sourceId,
      userSpecificToken: _consentUserToken,
   subjectIdentityValues: subjectIdentityValues,
      baseUrl: _baseUrl,
      fallback: _fallback,
      dynamicConsent: true,
    );
  }


  static final FallbackConfig _fallback = FallbackConfig(
    displayUrl: 'YOUR_FALLBACK_DISPLAY_URL',
    submitUrl: 'YOUR_FALLBACK_SUBMIT_URL',
    refreshCsrfToken: () async => 'YOUR_CSRF_TOKEN',
  );

  Future<void> _openConsentForm() async {
    final shouldOpen = await _shouldOpenConsentForm(_subjectIdentityValues);
    if (!shouldOpen!) {
      _showMessage('Consent already exists. Consent form is not required.');
      return;
    }

    await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => ConsentFormPage(
          token: _consentUserToken,
          sourceId: _sourceId,
          initialSubjectValues: _subjectIdentityValues,
          additionalParams: _additionalParams,
          baseUrl: _baseUrl,
          fallback: _fallback,
          enableCaptcha: false,
          callbacks: ConsentCallbacks(
            onSuccess: (
                int? statusCode,
                String? message,
                List<Map<String, dynamic>>? data,
                ) {
              debugPrint('Consent Submitted! Status: $statusCode');
              if (data != null) {
              }
            },
            onError: (int? statusCode, String? message) {
              debugPrint('Consent Failed! Status: $statusCode, Message: $message');
            },
            onClose: (String? message) {
              debugPrint('Consent Form Closed by User: $message');
            },
            onNothingTapped: (String? message) {
              _handleNothingTapped(message);
            },
          ),
        ),
      ),
    );
  }

  void _handleNothingTapped(String? buttonId) {
    debugPrint('the callback received on client app is : $buttonId');
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (dialogContext) => AlertDialog(
        title: const Text('Client Action Triggered'),
        content: Text(
          'Button "$buttonId" with "do_nothing" handler was tapped.\n\n'
          'The SDK consent form is currently open behind this overlay.\n'
          'Clicking "Complete Action & Close SDK" below will execute client logic '
          'and call GoTrustSdkHelper.closeConsentForm() from outside ConsentFormPage.',
        ),
        actions: [
          TextButton(
            onPressed: () {

              Navigator.of(dialogContext).pop();

              _performClientActionAndCloseSdk();
            },
            child: const Text('Complete Action & Close SDK'),
          ),
        ],
      ),
    );
  }

  void _performClientActionAndCloseSdk() {
    debugPrint('Client app performing custom operation...');
    _showMessage('Client operation completed. Closing SDK screen now...');


    GoTrustSdkHelper.closeConsentForm();
  }

  Future<void> _openPreferenceCenter() async {
    await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => LoginPage(
          pfToken: _pfToken,
          token: _pfUserToken,
          customerId: _customerId,
          preferenceFormId: _preferenceFormId,
          consentId: _sourceId,
          additionalParams: _additionalParams,
          baseUrl: _baseUrl,
          initialSubjectValues: _subjectIdentityValues,
          enableCaptcha: false,
        ),
      ),
    );
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GoTrust Flutter Sample'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              'Open Consent Form and Preference Center',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: 12),
            const Text(
              'Using hardcoded subject identity values:',
              style: TextStyle(fontSize: 12, color: Colors.black54),
            ),
            const SizedBox(height: 4),
            Text(
              _subjectIdentityValues.entries
                  .map((e) => '${e.key}: ${e.value}')
                  .join('\n'),
              style: const TextStyle(fontSize: 12, color: Colors.black54),
            ),
            const SizedBox(height: 16),
            FilledButton(
              onPressed: _openConsentForm,
              child: const Text('Open Consent Form'),
            ),
            const SizedBox(height: 12),
            OutlinedButton(
              onPressed: _openPreferenceCenter,
              child: const Text('Open Preference Center'),
            ),
          ],
        ),
      ),
    );
  }
}