Skip to main content

go_trust_mobile_sdk 1.1.1+9 copy "go_trust_mobile_sdk: ^1.1.1+9" to clipboard
go_trust_mobile_sdk: ^1.1.1+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 = 'https://preprod.gotrust.tech';

  static const String _sourceId =
      'A8EPl9A4PQCx0kdPsQZmLQg_V_1aS5D1Ok9Fdmq56OLVUg==';
  static const String _customerId =
      'QPKFEL4cJGzKiaOSa6fcqphzxPBo6YXHfPx12_KarA==';
  static const String _preferenceFormId =
      '0gR3uiz34fJBYV6sg5IC7qEmO4BVKWKrn1SWmrg0qA==';
  static const String _pfToken = "QdOb9snbbeiJzVO9HYkEdbzV-kctVkphecfaolFm31dXDpIMPoni3stxA_plxYinUTBtLzTjLzG0GIQxNs90";
  static const String _consentUserToken = "sqToNfBeohdiyUVCvHwtO2_OFeAQbVTj9935CLPFXXhfcsloKaE8adsCLOrzvWvFTS1Uhj5o8L0nNILVXIYnoxUeeqti8CtTI_aFJBXyE8oO-DwDVPm7mhEILrtmKGAPG4earb_q5eK8pAJymCnQfz8Od7Em7GudUSbEhQBE-u2C7iaIUliymUNP0qn_RC5bcCXVFiF3ROvqF6sf5HPGUifdKtAmssyJu8B0HxVFp03j3GSe3kWUvHwJDMuC8z6CB42JLEg0OEqa8gZZvO-BHD3azchjLr5cpFtPYZp_7ckGdbe0v-HIThoVFjvjleDdg_HNGaLqyAAXD3qVlOqNgNPOA5wFihZIw0nYrtV4rwa9yHt709bfnTtx_2MaBrqv47-nu1TyjEsRV3ZQgE3pxq11qzb4TS3Tq4rN47fziae2xZWgAqzHd-nvPQW-fl6fBc46vxHk5ej56XL3REnQaT6p";
  static const String _pfUserToken = "USER_SPECIFIC_PREFERENCE_CENTER_TOKEN";
  static const String _authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjMxNjIsImN1c3RvbWVyX2lkIjo2MzksImVtYWlsIjoic3lzdGVtQGdvdHJ1c3QudGVjaCIsInR5cGUiOiJTWVNURU1fVVNFUiIsImp0aSI6ImUxNGZiM2NkLThjZGYtNGIwYi1iNjJjLTU5ZGUyMzQ0MWQ2NCIsImlhdCI6MTc4OTczMDA3NiwiZXhwIjoxNzg5NzU4ODc2fQ.tySl3-dRQfTIB5947NVNgHdlxmBqSADiP53bzGctb3M";
  static const Map<String, dynamic> _subjectIdentityValues = {
    // "452": "9891737651",
    "18642": "132"
    // "106": "pratyush@appvintech.com"
  };


  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,
      // authToken: _authToken,
    );
  }


  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);
            },
          ),
          // authToken: _authToken,
        ),
      ),
    );
  }

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