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.
After the Flutter SDK is installed, you can use the client to evaluate flag rules like A/B tests and flag deliveries.
This example walks through the following three key steps:
-
Evaluate a flag with the key
product_sortusing thedecidemethod. This also sends a decision event to Optimizely to record that the user was exposed to the experiment. -
Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either
- Check the flag's enabled state and read a configuration variable (
sort_method) to determine which experience the user gets. - Check the flag variation directly and run the corresponding control or treatment code.
- Check the flag's enabled state and read a configuration variable (
-
Track a conversion event called
purchasedto measure the experiment's impact. ThetrackEventmethod ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment 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 3 days ago
