Initialize Flutter SDK
How to initialize the Optimizely Feature Experimentation Flutter SDK.
TheinitializeClient method initializes the Flutter SDK and instantiates an instance of the Optimizely Feature Experimentation SDK class, which exposes API methods like theCreateUserContext method. Each client corresponds to the datafile that represents the state of a project for an environment. The datafile is accessible throughOptimizelyConfig.
Version
2.0.0 or higher
Description
The constructor accepts a configuration object to configure Optimizely Feature Experimentation.
Some parameters are optional because the Flutter SDK provides a default implementation, but you may want to override these for your production environments. For example, you can set up event options to manage network calls and datafile handler parameters to set up the datafile download path or interval.
Parameters
start method parameters:
Parameter | Type | Description |
|---|---|---|
sdkKeyrequired | String | Each environment has its own SDK key. |
eventOptionsoptional | EventOptions | Lets you set If you do not set these values, the system uses the defaults of |
datafilePeriodicDownloadIntervaloptional | int | Sets the interval (in seconds) during which The minimum interval is 15 minutes (enforced by the Android JobScheduler API). If you are running iOS only, there is no minimum interval. |
datafileHostOptionsoptional | Map<ClientPlatform, DatafileHostOptions> | Adds support to provide custom
For each platform, the |
defaultDecideOptionsoptional | Set<OptimizelyDecideOption> | Sets default decide options applied to the |
sdkSettingsoptional | SDKSettings | You can configure other SDK settings, such as theReal-Time Audiences for Feature Experimentation methods with this |
// You must configure Real-Time Audiences for Feature Experimentation before using the following methods.class SDKSettings { // The maximum size of audience segments cache. Optional. default = 100. Set to 0 to disable caching. final int segmentsCacheSize; // The timeout in seconds of audience segments cache. Optional. Default = 600. Set to 0 to disable timeout. final int segmentsCacheTimeoutInSecs; // The timeout in seconds of ODP segment fetch. Optional. Default = 1) - The OS default timeout is used if this is set to 0. final int timeoutForSegmentFetchInSecs; // The timeout in seconds of ODP event dispatch. Optional. Default = 10 - The OS default timeout is used if this is set to 0. final int timeoutForOdpEventInSecs; // Set this flag to true to disable ODP features. Default = false. final bool disableOdp; // Set this flag to true to enable VUID feature. Default = false. final bool enableVuid;}Returns
Instantiates an instance of the Optimizely Feature Experimentation class.
Customize ODPManager
OdpManager contains the logic supportingReal-Time Audiences for Feature Experimentation-related features, including audience segments.
📘
InformationIf necessary, to disable Real-Time Audiences for Feature Experimentation altogether, set
disableOdptotrue.
The followingSDKSettings are optionally configurable when the Flutter SDK is initialized:
- ODP SegmentsCache size –
segmentsCacheSize- Default – 100
- Set to 0 to disable caching.
- ODP SegmentsCache timeout (in seconds) –
segmentsCacheTimeoutInSecs- Default – 600 secs (10 minutes)
- Set to 0 to disable timeout (never expires).
- ODP SegmentsFetch timeout –
timeoutForSegmentFetchInSecs- Default – 10 secs
- The Operating System's (OS) default timeout is used if this is set to zero.
- ODP Event timeout –
timeoutForOdpEventInSecs- Default – 10 secs
- OS default timeout is used if this is set to 0.
- ODP enable/disable –
disableOdp- Default –
false(Enabled) - When
disableOdpis set totrue, the Flutter SDK disables ODP-related features. The Flutter SDK still creates and manages VUID regardless of this flag and supports VUID-based decisions. Seeanonymous users. - The Flutter SDK returns or logs an
odpNotEnablederror when ODP is disabled and its features are requested.
- Default –
- enableVUID – enableVuid
🚧
ImportantOnly available on the Flutter SDK version 3.0.0+. SeeSDK compatibility matrix.
- Default –
false(Disabled) - When enabled, the Flutter SDK creates and manages VUID and supports VUID-based decisions. Seeanonymous users.
- Default –
// You must configure Real-Time Audiences for Feature Experimentation before using the following methods.class SDKSettings { // The maximum size of audience segments cache. Optional. default = 100. Set to 0 to disable caching. final int segmentsCacheSize; // The timeout in seconds of audience segments cache. Optional. Default = 600. Set to 0 to disable timeout. final int segmentsCacheTimeoutInSecs; // The timeout in seconds of ODP segment fetch. Optional. Default = 10 - The OS default timeout is used if this is set to 0. final int timeoutForSegmentFetchInSecs; // The timeout in seconds of ODP event dispatch. Optional. Default = 10 -The OS default timeout is used if this is set to 0. final int timeoutForOdpEventInSecs; // Set this flag to true to disable ODP features. Default = false. final bool disableOdp;}You can providesegmentsCacheSize andsegmentsCacheTimeoutInSecs timeout by passing these values when initializing the Flutter SDK.
const odpSettings = SDKSettings( segmentsCacheSize: 1000, segmentsCacheTimeoutInSecs: 30 * 60, disableOdp: false); var flutterSDK = OptimizelyFlutterSdk("YOUR_SDK_KEY", sdkSettings: odpSettings); var response = await flutterSDK.initializeClient();Examples
You do not need to manage the datafile directly in the Flutter SDK. The SDK includes a datafile manager that provides support for datafile polling to automatically update the datafile at a regular interval while the application is in the foreground.
To use it complete the following:
Create a
OptimizelyFlutterSdkby supplying yourSDK Key and optional configuration settings. You can find the SDK key inSettings > Environments of a Feature Experimentation project.To start the clientsynchronously and use the
initializeClientmethod to instantiate a client:// Initializing Optimizely Clientvar flutterSDK = OptimizelyFlutterSdk("YOUR_SDK_KEY");var response = await flutterSDK.initializeClient();// flag decisionvar user = await flutterSDK.createUserContext(userId: "USER_ID");var decideResponse = await user!.decide("FLAG_KEY");
Use initialization
Instantiate the Optimizely client synchronously. During initialization, the SDK fetches the latest datafile from the Feature Experimentation servers.
During initialization, your app requests the newest datafile from the CDN servers. Requesting the newest datafile ensures that your app uses the latest project settings. It also means your app cannot instantiate a client until it downloads a new datafile, discovers the datafile has not changed, or the request times out.
Initializing a client synchronously causes the manager to first attempt to download the newest datafile. The network activity causes an initialization to take longer to complete.
If the network request returns an error, such as when network connectivity is unreliable or if the manager discovers that the cached datafile is identical to the newest datafile, the Optimizely Feature Experimentation manager searches for acached datafile. If one is available, the manager uses the datafile to complete the client initialization; otherwise initialization fails. If the manager discovers there is an updated datafile that differs from the cached datafile, the manager downloads the new datafile and uses it to initialize the client.

To initialize anOptimizelyClient object, callflutterSDK.initializeClient().
Configure datafile polling
Datafile polling is the process of checking for and downloading a new datafile. After the manager tries to pull the latest datafile from the CDN servers, the Optimizely manager periodically checks for and pulls a new datafile at the time interval you set during its initialization.
Datafile polling is enabled by default. You can set a non-zero interval value to increase or decrease the polling interval. This value is the number of seconds the manager waits between datafile polling attempts.
// Datafile update interval can be configured when the SDK is configured// Background datafile update is disabled if periodicDownloadInterval is zerovar flutterSDK = OptimizelyFlutterSdk("<Your_SDK_Key>", datafilePeriodicDownloadInterval: 15 * 60);// every 15 minutesUsage notes
The minimum polling interval is 15 minutes while the app is open. You cannot set a shorter polling interval.
The Optimizely manager only checks for new datafiles when the SDK is active, and the app runs on iOS, tvOS, or Android.
The Flutter SDK automatically updates when it detects a new datafile to ensure you are always working with the latest datafile. If you want to receive a notification when the project updates, register for a datafile change through the datafile change notification listener. You can also register for datafile change notifications using the
UpdateConfigNotificationmethod.
flutterSDK.addConfigUpdateNotificationListener((msg) { print("got datafile change"); });Dispose of the client
For effective resource management with the Optimizely Flutter SDK, you must properly close the Optimizely client instance when it is no longer needed. This is done by calling.close.
The.close() method ensures that the processes and queues associated with the instance are properly released. This is essential for preventing memory leaks and ensuring that the application runs efficiently, especially in environments where resources are limited or in applications that create and dispose of many instances over their lifecycle.
SeeClose Optimizely Feature Experimentation Flutter SDK on application exit.
More sample code
// Initializing OptimizelyClient without optional parametersvar flutterSDK = OptimizelyFlutterSdk("<Your_SDK_Key>");var response = await flutterSDK.initializeClient();// flag decisionvar user = await flutterSDK.createUserContext(userId: "<User_ID>");var decideResponse = await user!.decide("<Flag_Key>"); // Initializing OptimizelyClient with optional datafilePeriodicDownloadIntervalvar flutterSDK = OptimizelyFlutterSdk(sdkKey, datafilePeriodicDownloadInterval: 16 * 60);var response = await flutterSDK.initializeClient();// flag decisionvar user = await flutterSDK.createUserContext(userId: "<User_ID>");var decideResponse = await user!.decide("<Flag_Key>");Source files
The language and platform source files containing the implementation for Flutter are available onGitHub.
Updated 17 days ago