Skip to main content

go_trust_mobile_sdk 1.0.5 copy "go_trust_mobile_sdk: ^1.0.5" to clipboard
go_trust_mobile_sdk: ^1.0.5 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_PREFERENCE_ID';
  static const String _token = "YOUR_TOKEN";

  // Hardcoded field-id : value pairs identifying the subject, so the
  // multi-identity flow can be tested with a single tap — no input needed.
  // Field ids come from your GoTrust form configuration (e.g. "107" = phone,
  // "10085" = email). Add/remove entries here to try different combinations.
  static const Map<String, dynamic> _subjectIdentityValues = {
    "2026": "go-trust@yopmail.com",
  };

  // Optional extra field-id : value pairs — not used for consent lookup,
  // just prefilled into the form.
  static const Map<String, dynamic> _additionalParams = {

  };

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

  // Flip to true to make the display API fail (unreachable host) so the
  // fallback display/submit endpoints below get exercised. Leave false for
  // normal runs.
  static const bool _forceDisplayApiFailure = true;

  // Stand-in fallback endpoints for manual testing: httpbin.org/post just
  // echoes back whatever JSON body it receives with a 200, so you can watch
  // the fallback payload show up in the response/logs.
  static final FallbackConfig _fallback = FallbackConfig(
    displayUrl: 'YOUR_DISPLAY_URL',
    submitUrl: 'YOUR_SUBMIT_URL',
    refreshCsrfToken: () async => 'dummy-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(
          sourceId: _sourceId,
          // customerId: _customerId,
          initialSubjectValues: _subjectIdentityValues,
          additionalParams: _additionalParams,
          // Unreachable host -> getConsentFormData's http.post throws ->
          // res stays null -> isServerError is true -> switches to fallback.
          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) {
                print("Received data: $data");
              }
            },
            onError: (int? statusCode, String? message) {
              debugPrint('Consent Failed! Status: $statusCode, Message: $message');
            },
            onClose: (String? message) {
              debugPrint('Consent Form Closed by User: $message');
            },
          ),
        ),
      ),
    );
  }

  Future<void> _openPreferenceCenter() async {
    await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => LoginPage(
          pfToken: _token,
          // 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'),
            ),
          ],
        ),
      ),
    );
  }
}