Example usage of the Flutter SDK
A brief code example of how to use the Optimizely Feature Experimentation Flutter SDK to evaluate feature flags, activate A/B tests, or feature tests.
You are ready to use the client to evaluate flag rules, including A/B tests and flag deliveries.
This example demonstrates the basic usage of each of the following concepts:
-
Evaluate a flag with the key
product_sort
using the Decide method. As a side effect, the Decide function also sends a decision event to Optimizely Feature Experimentation to record that the system exposed the current user to the experiment. -
Execute your feature code conditionally. You have a couple of options:
- Fetch the flag-enabled state, then check a configuration variable on the flag called
sort_method
. The SDK evaluates your flag rules and determines what flag variation the user is in and which sort method variable to display. - Fetch the flag variation, then run the 'control' or 'treatment' code.
- Use event tracking to track an event called
purchased
. This conversion event measures the impact of an experiment. Using the Track Event method, the system automatically attributes the purchase back to the running A/B test we made a decision for and the SDK sends a network request to Optimizely Feature Experimentation using the customizable event dispatcher, so Optimizely can count it on your results page.
// Initializing OptimizelyClient
var flutterSDK = OptimizelyFlutterSdk("<Your_SDK_Key>");
var response = await flutterSDK.initializeClient();
// flag decision
var user = await flutterSDK.createUserContext(userId: "user123");
var attributes = <String, dynamic>{};
attributes["logged_in"] = true;
user!.setAttributes(attributes);
var decideResponse = await user.decide("product_sort");
// did the decision fail with a critical error?
if (!decideResponse.success) {
var reason = decideResponse.reason;
print("decision error: $reason");
}
var decision = decideResponse.decision;
var variationKey = decision!.variationKey;
// execute code based on flag enabled state
var enabled = decision.enabled;
var variables = decision.variables;
if (enabled) {
String vs;
try {
vs = variables["sort_method"] as String;
} catch (ex) {
print(ex);
}
}
// or execute code based on flag variation:
if (variationKey == "control") {
// Execute code for control variation
} else if (variationKey == "treatment") {
// Execute code for treatment variation
}
// Track an event
user.trackEvent("purchased");
Updated 11 months ago