requestConsent method

Future<ConsentResult> requestConsent({
  1. ConsentDebugSettings? debugSettings,
})

Requests consent information and shows the consent form if required.

Implementation

Future<ConsentResult> requestConsent({
  ConsentDebugSettings? debugSettings,
}) async {
  if (!AdConstants.isPlatformSupported) {
    developer.log(
      'ConsentManager: Platform not supported for UMP consent. Returning canRequestAds = false.',
      name: 'ConsentManager',
    );
    return const ConsentResult(canRequestAds: false);
  }

  final completer = Completer<ConsentResult>();

  final params = ConsentRequestParameters(
    consentDebugSettings: debugSettings,
  );

  ConsentInformation.instance.requestConsentInfoUpdate(
    params,
    () async {
      ConsentForm.loadAndShowConsentFormIfRequired(
        (formError) async {
          if (formError != null) {
            developer.log(
              'Consent form error: ${formError.message} (code: ${formError.errorCode})',
              name: 'ConsentManager',
            );
          }

          final canRequestAds =
              await ConsentInformation.instance.canRequestAds();
          if (!completer.isCompleted) {
            completer.complete(
              ConsentResult(
                canRequestAds: canRequestAds,
                error: formError,
              ),
            );
          }
        },
      );
    },
    (formError) async {
      developer.log(
        'Failed to update consent info: ${formError.message} (code: ${formError.errorCode})',
        name: 'ConsentManager',
      );
      // Google UMP Policy & Guideline: Check if consent is already cached locally from previous session
      final canRequestAds =
          await ConsentInformation.instance.canRequestAds();
      if (!completer.isCompleted) {
        completer.complete(
          ConsentResult(
            canRequestAds: canRequestAds,
            error: formError,
          ),
        );
      }
    },
  );

  return completer.future;
}