Orientação gerada a partir de informações públicas. Apenas para referência.
The growthbook_sdk_flutter package is an open-source feature flagging and experimentation platform that enables developers to dynamically control feature availability and run A/B tests without deploying new code. It integrates seamlessly into Flutter apps across Android, iOS, macOS, Windows, and Linux, allowing teams to test hypotheses, roll out features gradually, and personalize user experiences. With real-time flag evaluation and robust analytics support, it simplifies experimentation at scale. The SDK is lightweight, easy to set up, and designed for flexibility in both development and production environments.
Casos de uso
Testes A/B de mudanças na interface do usuário
lançamentos graduais de funcionalidades
Segmentação de usuários com base em atributos
Alternância de recursos em tempo real
Experimentação com configurações de variáveis
Experiências personalizadas do usuário
Principais recursos
Avaliação em tempo real de sinalizadores de recurso
Suporte para testes A/B e multivariados
Gerenciamento de flags do lado do cliente e do lado do servidor
Direcionamento baseado em atributos
Integração fácil com aplicativos Flutter
Compatibilidade multiplataforma
Indicado para
Equipes que realizam experimentos frequentes
Gerentes de produto que precisam de iteração rápida
Desenvolvedores implementando controle de recurso dinâmico
Startups escalando a entrega de recursos
Equipes de engenharia focadas em decisões baseadas em dados
Aplicativos que exigem experiências personalizadas do usuário
Considerações
Requer configuração de backend para capacidades completas de experimentação
Pode aumentar levemente o tamanho do pacote do aplicativo
Necessita de tratamento adequado de erros em cenários offline
Dependente da API do GrowthBook para configuração remota
Melhor usado com uma estratégia de experimentação definida
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
GrowthBook is an open source feature flagging and experimentation platform. This Flutter SDK allows you to use GrowthBook with your Flutter based mobile application.
Platform Support:
📱 Android 21+ • iOS 12+
📺 tvOS 13+ • ⌚ watchOS 7+
🖥️ macOS • Windows • Linux
🌐 Web (Flutter Web)
✨ Features
Lightweight - Minimal performance impact
Type Safe - Full Dart/Flutter type safety
Caching - Smart caching with TTL and stale-while-revalidate
Cross-platform - Works on Android, iOS, Web, Desktop
🏗️ Core Capabilities
Feature Flags - Toggle features on/off without code deployments
A/B Testing - Run experiments with statistical significance
Targeting - Advanced user segmentation, variation weights and targeting rules
Tracking - Use your existing event tracking (GA, Segment, Mixpanel, custom)
Real-time Updates - Features update instantly via streaming
🎯 Advanced Features
Sticky Bucketing - Consistent user experiences across sessions
Remote Evaluation - Server-side evaluation for enhanced security
Multi-variate Testing - Test multiple variations simultaneously
Rollout Management - Gradual feature rollouts with traffic control
final sdk = awaitGBSDKBuilderApp(
apiKey: "your_api_key",
growthBookTrackingCallBack: (trackData) {
final experiment = trackData.experiment;
final result = trackData.experimentResult;
// Google AnalyticsFirebaseAnalytics.instance.logEvent(
name: 'experiment_viewed',
parameters: {
'experiment_id': experiment.key,
'variation_id': result.variationID,
'variation_name': result.key,
},
);
// MixpanelMixpanel.track('Experiment Viewed', {
'Experiment ID': experiment.key,
'Variation ID': result.variationID,
});
// Custom analyticsYourAnalytics.trackExperiment(experiment, result);
},
).initialize();
📚 Documentation
Configuration Options
final sdk = awaitGBSDKBuilderApp(
// Required
apiKey: "sdk_your_api_key",
hostURL: "https://growthbook.io",
// User Context
attributes: {
'id': 'user_123',
'email': 'user@example.com',
'plan': 'premium',
'country': 'US',
},
// Performance & Caching
ttlSeconds: 300, // Cache TTL (default: 60s)
backgroundSync: true, // Real-time updates// Testing & QA
qaMode: false, // Disable randomization for QA
forcedVariations: { // Force specific variations'button_test': 1,
},
// Analytics Integration
growthBookTrackingCallBack: (trackData) {
// Send to your analytics platformfinal experiment = trackData.experiment;
final result = trackData.experimentResult;
analytics.track('Experiment Viewed', {
'experiment_id': experiment.key,
'variation_id': result.variationID,
'variation_name': result.key,
});
},
// Advanced Features
remoteEval: false, // Server-side evaluation
encryptionKey: "...", // For encrypted features
).initialize();
Configuring Log Level
The SDK logs internal events (feature evaluation skips, cache errors, refresh
attempts) through a logger package instance. Verbosity is controlled by
GrowthBookSDK.setLogLevel(...), which accepts an SDK-owned GBLogLevel enum:
import'package:growthbook_sdk_flutter/growthbook_sdk_flutter.dart';
voidmain() {
// Configure once at app startup — before initializing the SDK.GrowthBookSDK.setLogLevel(GBLogLevel.debug);
runApp(constMyApp());
}
Available levels: verbose, debug, info, warning (default), error, off.
⚠️ Process-global: log level is shared across all GrowthBookSDK instances
in the same process. Set it once at app startup rather than per-instance.
If you run multiple SDK instances, they will share the same verbosity.
// Define experimentfinal experiment = GBExperiment(
key: 'checkout_button_test',
variations: ['🛒 Buy Now', '💳 Purchase', '✨ Get It Now'],
weights: [0.33, 0.33, 0.34], // Traffic distribution
);
// Run experimentfinal result = sdk.run(experiment);
// Use resultWidgetbuildButton() {
final buttonText = result.value ?? '🛒 Buy Now';
returnElevatedButton(
onPressed: () => handlePurchase(),
child: Text(buttonText),
);
}
// Track conversionif (purchaseCompleted) {
// Your analytics will receive this via trackingCallBack
}
User Attributes & Targeting
// Update user attributes dynamically
sdk.setAttributes({
'plan': 'enterprise',
'feature_flags_enabled': true,
'last_login': DateTime.now().toIso8601String(),
});
// Target users with conditions// Example: Show feature only to premium users in US// This is configured in GrowthBook dashboard, not in code
Condition Operators
The SDK supports the following operators in targeting conditions:
Comparison
Operator
Description
$eq
Equal to
$ne
Not equal to
$lt
Less than
$lte
Less than or equal
$gt
Greater than
$gte
Greater than or equal
Membership
Operator
Description
$in
Value is in array
$nin
Value is not in array
$all
Array contains all values
$ini
Value is in array (case-insensitive string comparison)
$nini
Value is not in array (case-insensitive string comparison)
$alli
Array contains all values (case-insensitive string comparison)
For $ini, $nini, and $alli: string values are compared after lowercasing; non-string values (numbers, booleans, null) are compared as-is.
Regex
Operator
Description
$regex
Matches regex (case-sensitive)
$notRegex
Does not match regex (case-sensitive)
$regexi
Matches regex (case-insensitive)
$notRegexi
Does not match regex (case-insensitive)
Other
Operator
Description
$exists
Attribute exists (true) or is absent (false)
$type
Attribute type matches string ("string", "number", "boolean", "array", "object", "null")
Ensure consistent user experiences across sessions:
classMyAppStickyBucketServiceextendsGBStickyBucketService{
@overrideFuture<Map<String, String>?> getAllAssignments(
Map<String, dynamic> attributes,
) async {
// Retrieve from local storagefinal prefs = awaitSharedPreferences.getInstance();
final json = prefs.getString('gb_sticky_assignments');
return json != null ? jsonDecode(json) : null;
}
@overrideFuture<void> saveAssignments(
Map<String, dynamic> attributes,
Map<String, String> assignments,
) async {
// Save to local storagefinal prefs = awaitSharedPreferences.getInstance();
await prefs.setString('gb_sticky_assignments', jsonEncode(assignments));
}
}
// Use with SDKfinal sdk = awaitGBSDKBuilderApp(
apiKey: "your_api_key",
stickyBucketService: MyAppStickyBucketService(),
).initialize();
Remote Evaluation
The Flutter SDK may be run in Remote Evaluation mode. This mode brings the security benefits of a backend SDK to the front end by evaluating feature flags exclusively on a private server. Using Remote Evaluation ensures that any sensitive information within targeting rules or unused feature variations are never seen by the client.
You must enable Remote Evaluation in your SDK Connection settings. Cloud customers are also required to self-host a GrowthBook Proxy Server or a custom remote evaluation backend.
To use Remote Evaluation, add the remoteEval: true property to your SDK instance.
final sdk = awaitGBSDKBuilderApp(
apiKey: "your_api_key",
remoteEval: true, // Enable remote evaluation
attributes: userAttributes,
).initialize();
// Features are evaluated server-side// Sensitive targeting rules never reach the client
Real-time Updates
The GrowthBook SDK supports streaming with Server-Sent Events (SSE). When enabled, changes to features within GrowthBook will be streamed to the SDK in realtime as they are published. This is only supported on GrowthBook Cloud or if running a GrowthBook Proxy Server.
final sdk = awaitGBSDKBuilderApp(
apiKey: "your_api_key",
backgroundSync: true, // Enable streaming updates
).initialize();
// Features automatically update when changed in GrowthBook// No need to restart the app or refresh manually
Tracking Plugins
Plugins observe SDK lifecycle events (feature evaluated, experiment viewed) and can implement custom side effects such as forwarding events to an analytics backend. The SDK ships with GrowthBookTrackingPlugin, which batches events and sends them to the GrowthBook ingest endpoint.
Tracking plugins buffer events in memory to reduce network overhead. You must call await sdk.dispose() when the SDK instance is no longer needed so buffered events are flushed and any resources (timers, HTTP clients) are released. Without this, queued tracking events will be dropped during app shutdown.
Extend GrowthBookPlugin to implement your own tracking, logging, or analytics forwarding:
classMyAnalyticsPluginextendsGrowthBookPlugin{
@overridevoidinitialize(String clientKey) {
// one-time setup (e.g. start a periodic flush timer)
}
@overridevoidonFeatureEvaluated(String id, GBFeatureResult result, Map<String, dynamic>? attributes) {
// forward to your analytics
}
@overridevoidonExperimentViewed(GBExperiment experiment, GBExperimentResult result, Map<String, dynamic>? attributes) {
// forward to your analytics
}
@overrideFuture<void> close() async {
// flush any buffered state, release resources
}
}
⚠️ Plugin errors are isolated per plugin — a throw in one plugin's callback does not affect other plugins or SDK evaluation. If you need stronger delivery guarantees than best-effort batching, implement retry/requeue with bounded storage inside your plugin's close() method.
💡 Examples
E-commerce App
classProductPageextendsStatelessWidget{
@overrideWidgetbuild(BuildContext context) {
final sdk = context.read<GrowthBookSDK>();
// Feature flagsfinal showReviews = sdk.feature('show_product_reviews').on;
final freeShipping = sdk.feature('free_shipping_threshold').value ?? 50.0;
// A/B test for pricing displayfinal pricingExperiment = GBExperiment(key: 'pricing_display_test');
final pricingResult = sdk.run(pricingExperiment);
returnScaffold(
body: Column(
children: [
ProductImage(),
ProductTitle(),
// Dynamic pricing display based on A/B testif (pricingResult.value == 'with_discount')
PricingWithDiscount()
elseStandardPricing(),
// Conditional featuresif (showReviews) ProductReviews(),
if (freeShipping > 0) FreeShippingBanner(threshold: freeShipping),
AddToCartButton(),
],
),
);
}
}