initialize static method

Future<CloudXInitializationResult> initialize({
  1. required String appKey,
})

Initializes the SDK with the provided appKey.

Never throws. A failure is reported as a CloudXInitializationResult with success false, carrying the native SDK's error code and message.

While a call is in flight, and after one has succeeded, a further call returns that outcome rather than initializing again. After a failed outcome a further call starts a fresh attempt: both native SDKs allow one, so a failure caused by the network or by a bad app key is recoverable without restarting the app.

Implementation

static Future<CloudXInitializationResult> initialize({
  required String appKey,
}) async {
  if (_hasInitializeBeenCalled) {
    return _initializeCompleter?.future ??
        Future.value(
          const CloudXInitializationResult(
            success: false,
            message: 'Initialization is already in progress',
          ),
        );
  }
  _hasInitializeBeenCalled = true;
  _initializeCompleter = Completer<CloudXInitializationResult>();

  _methodChannel.setMethodCallHandler(_handleNativeMethodCall);

  try {
    // Hot restart detection - check if native SDK already initialized
    final isPlatformSDKInitialized = await isInitialized();
    if (isPlatformSDKInitialized) {
      _log('SDK already initialized (hot restart detected)');
      _initializeCompleter!
          .complete(const CloudXInitializationResult(success: true));
      return await _initializeCompleter!.future;
    }

    final result = await _invokeMethod<Map<dynamic, dynamic>>('initialize', {
      'appKey': appKey,
      'pluginVersion': 'flutter-$_pluginVersion',
    });

    final outcome = CloudXInitializationResult.fromMap(result);
    if (!outcome.success) {
      _log('Initialization failed: ${outcome.message}');
    }
    final completer = _initializeCompleter!;
    _releaseInitializeGateOnFailure(outcome);
    completer.complete(outcome);
    return await completer.future;
  } catch (e) {
    /*
     * The platform channel itself failed, so there is no native error to
     * report. PlatformException carries a code, but it is the channel's own
     * code rather than a CloudXErrorCode, so only the message is passed on.
     */
    _log('Initialization failed: $e');
    final outcome = CloudXInitializationResult(
      success: false,
      message: e.toString(),
    );
    final completer = _initializeCompleter!;
    _releaseInitializeGateOnFailure(outcome);
    if (!completer.isCompleted) {
      completer.complete(outcome);
    }
    return completer.future;
  }
}