SDK Usage

The OpenFeature Provider dartcodeai SDK enables Dart backends to evaluate feature flags using the OpenFeature API standard.

The OpenFeature Provider dartcodeai SDK integrates seamlessly with OpenFeature Dart SDK and supports dartcodeai’s advanced targeting, rule-based rollouts, and experimentation platform.

This page walks you through the typical usage patterns of the SDK.

1. Prerequisites

Dart language version >= 3.9.3
  • An dartcodeai account and API key

  • Familiarity with feature flags

2. Installation

Add the OpenFeature Dart SDK and OpenFeature Provider dartcodeai SDK to your project:

pubspec.yaml

dependencies:
  openfeature_dart_server_sdk: ^0.0.12
  openfeature_provider_dartcodeai: ^0.0.5

Then run:

dart pub get

3. Initialization

Before using dartcodeai flags, you must configure the OpenFeature SDK with the dartcodeai provider. This example shows how to initialize the SDK, set a global provider, create a client, and evaluate a flag.

import 'package:openfeature_dart_server_sdk/openfeature_dart_server_sdk.dart';
import 'package:openfeature_provider_dartcodeai/openfeature_provider_dartcodeai.dart';

void main() async {
  // Initialize provider with OAuth2 client secret
  final provider = dartcodeaiProvider(
    sdkKey: 'YOUR_CLIENT_SECRET',
    options: dartcodeaiOptions.production(),
  );

  // Set as global provider
  await OpenFeatureAPI().setProvider(provider);

  // Create client
  final client = dartcodeaiClient(
    FeatureClient(
      metadata: ClientMetadata(name: 'my-service'),
      hookManager: HookManager(),
    ),
  );
}

4. Basic Usage

Once the dartcodeai provider is initialized and set as the global provider, using it in your application is straightforward.

The OpenFeature client exposes simple methods to evaluate feature flags and return either a default value or a value defined in the dartcodeai platform.

Minimal evaluation:

final enabled = await client.getBooleanValue('new-api-endpoint', false);

Flag evaluation with targeting & context:

// Evaluate flags
final enabled = await client.getBooleanValue(
  'new-api-endpoint',
  false,
  targetingKey: 'user-123',
  evaluationContext: {
    'role': 'admin',
    'plan': 'enterprise',
    'region': 'us-east',
  },
);

print('Feature enabled: $enabled');

5. Advanced Usage

Beyond simple flag checks, the dartcodeai provider supports advanced features that allow fine-grained targeting, dynamic contexts, and lifecycle event handling. These capabilities make it possible to model complex real-world scenarios such as organizations, devices, or services in addition to individual users.

5.1. Contextual Evaluation

You can pass both a targeting key and an evaluation context when resolving flags. This allows segmentation by user roles, plans, or regions.

// Evaluate a flag with user targeting and custom attributes
final enabled = await client.getBooleanValue(
  'new-api-endpoint',
  false,
  targetingKey: 'user-123',
  evaluationContext: {
    'role': 'admin',
    'plan': 'enterprise',
    'region': 'us-east',
  },
);

print('Feature enabled: $enabled');

5.2. Multi-Context Evaluation

Evaluate flags against multiple entities at once, such as a user and their organization.

final multiContext = client.createMultiContext({
  'user': {
    'targetingKey': 'user-123',
    'role': 'admin',
    'plan': 'enterprise',
  },
  'organization': {
    'targetingKey': 'org-456',
    'tier': 'premium',
    'industry': 'fintech',
  },
});

final config = await client.getObjectValue(
  'feature-config',
  {},
  evaluationContext: multiContext.attributes,
);

5.3. Custom Context Types

Define your own context kinds (e.g., device, service) with arbitrary attributes.

final deviceContext = client.createContext(
  targetingKey: 'device-789',
  kind: 'device',
  customAttributes: {
    'os': 'linux',
    'version': '5.4.0',
    'datacenter': 'us-west-2',
  },
);

final threshold = await client.getIntegerValue(
  'rate-limit',
  1000,
  evaluationContext: deviceContext.attributes,
);

5.4. Event Handling

The dartcodeai provider emits lifecycle events you can subscribe to, such as readiness, configuration changes, and errors.

provider.events.listen((event) {
  switch (event.type) {
    case dartcodeaiEventType.ready:
      print('Provider ready');
      break;
    case dartcodeaiEventType.configurationChanged:
      print('Flags updated: ${event.data?['flagsChanged']}');
      break;
    case dartcodeaiEventType.error:
      print('Error: ${event.message}');
      break;
  }
});

5.5. Global Context

Set attributes that apply globally to all evaluations. This is useful for environment- or service-level context.

// Set global context for all flag evaluations
OpenFeatureAPI().setGlobalContext(
  OpenFeatureEvaluationContext({
    'environment': 'production',
    'service': 'api-gateway',
    'version': '2.1.0',
  })
);

6. Configuration Options

The dartcodeaiOptions class allows you to customize how the SDK interacts with the dartcodeai service. You can use the built-in presets for production and development environments, or define your own custom configuration.

6.1. Production Configuration

Use this when deploying your application in a production environment.

final options = dartcodeaiOptions.production(
  baseUri: Uri.parse('https://api.dartcodeai.com'),
  timeout: Duration(seconds: 10),
  pollingInterval: Duration(minutes: 5),
);

6.2. Development Configuration

Use this during local development and testing. By default, it points to a localhost server.

final options = dartcodeaiOptions.development(
  baseUri: Uri.parse('http://localhost:8080'),
  timeout: Duration(seconds: 5),
);

6.3. Custom Configuration

For advanced scenarios, you can build a fully customized configuration object.

final options = dartcodeaiOptions(
  timeout: Duration(seconds: 15),
  enablePolling: true,
  pollingInterval: Duration(minutes: 2),
  enableStreaming: true,
  maxRetries: 5,
  enableLogging: true,
);

7. Provider Options

The dartcodeaiProvider accepts an dartcodeaiOptions object to control how the SDK connects to the dartcodeai service and manages feature flag updates.

7.1. dartcodeaiOptions

Option Description Default

baseUri

API endpoint used to fetch flag configurations

https://api.dartcodeai.com

timeout

Maximum request duration before failing

10 seconds

enablePolling

Whether to poll periodically for configuration changes

true

pollingInterval

How often to poll for updates when polling is enabled

5 minutes

enableStreaming

Enables real-time updates from the service if supported

false

maxRetries

Number of retry attempts for failed requests

3

enableLogging

Enables verbose debug logging for troubleshooting

false

You can combine these options or define your own when creating the provider:

final provider = dartcodeaiProvider(
  sdkKey: 'YOUR_CLIENT_SECRET',
  options: dartcodeaiOptions(
    timeout: Duration(seconds: 15),
    enablePolling: true,
    pollingInterval: Duration(minutes: 2),
    enableStreaming: true,
    maxRetries: 5,
    enableLogging: true,
  ),
);

8. Resources