diff --git a/example/lib/my_app.dart b/example/lib/my_app.dart index 771f5bb..6f1a3b7 100644 --- a/example/lib/my_app.dart +++ b/example/lib/my_app.dart @@ -30,7 +30,7 @@ class _MyAppState extends State { late Amplitude analytics; initAnalytics() async { - await analytics.init(); + await analytics.isBuilt; setMessage('Amplitude initialized'); } diff --git a/lib/amplitude.dart b/lib/amplitude.dart index 80277fd..7c1d5d2 100644 --- a/lib/amplitude.dart +++ b/lib/amplitude.dart @@ -12,26 +12,36 @@ import 'package:amplitude_flutter/events/group_identify_event.dart'; class Amplitude { Configuration configuration; MethodChannel _channel = const MethodChannel("amplitude_flutter"); - - /// Returns an Amplitude instance + /// Whether the Amplitude instance has been successfully initialized /// - /// Call `init()` to initialize underlying SDKs on native platforms /// ``` /// var amplitude = Amplitude(Configuration(apiKey: "apiKey")); - /// await amplitude.init(); + /// // If care about init complete + /// await amplitude.isBuilt; /// ``` - Amplitude(this.configuration); + late Future isBuilt; - /// Initializes an Amplitude instance + /// Returns an Amplitude instance /// /// ``` /// var amplitude = Amplitude(Configuration(apiKey: "apiKey")); - /// await amplitude.init(); + /// // If care about init complete + /// await amplitude.isBuilt; /// ``` - Future init([MethodChannel? methodChannel]) async { + Amplitude(this.configuration, [MethodChannel? methodChannel]){ _channel = methodChannel ?? this._channel; - return await _channel.invokeMethod( - "init", this.configuration.toMap()); + isBuilt = _init(); + } + + /// Private method to initialize and return a Future + Future _init() async { + try { + await _channel.invokeMethod("init", configuration.toMap()); + return true; // Initialization successful + } catch (e) { + print("Error initializing Amplitude: $e"); + return false; // Initialization failed + } } /// Tracks an event. Events are saved locally. diff --git a/test/amplitude_test.dart b/test/amplitude_test.dart index a089422..c112510 100644 --- a/test/amplitude_test.dart +++ b/test/amplitude_test.dart @@ -100,8 +100,8 @@ void main() { mockChannel = MockMethodChannel(); when(mockChannel.invokeListMethod("init", any)) .thenAnswer((_) async => null); - amplitude = Amplitude(testConfiguration); - await amplitude.init(mockChannel); + amplitude = Amplitude(testConfiguration, mockChannel); + await amplitude.isBuilt; }); test("Should init and track call MethodChannel", () async {