Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/v6-major-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
- **Breaking:** rename `enable()` and `disable()` to `optIn()` and `optOut()` on `PosthogFlutterPlatformInterface`, `PosthogFlutterIO` and `PosthogFlutterWeb`
- **Breaking:** adopt `posthog-ios` 4.x, which requires Xcode 26
- **Breaking:** adopt `posthog-android` 4.x
- **Breaking:** pass a `PostHogFeatureFlagsLoaded` with the enabled flags, their values and whether loading failed to `PostHogConfig.onFeatureFlags` — update callbacks from `() { ... }` to `(loaded) { ... }` or `(_) { ... }`
- **Breaking:** remove `PostHogConfig.onFeatureFlags` — call `Posthog().onFeatureFlags((loaded) { ... })` before `setup()` instead, which also covers the first load
- **Breaking:** return the reloaded flags from `reloadFeatureFlags()` as a `Future<PostHogFeatureFlagsLoaded>`
- **Breaking:** return `null` instead of the raw string for a malformed, empty or whitespace-only `getFeatureFlagResult()` payload on iOS, macOS and Android
- **Breaking:** keep string payloads passed to `PostHogBootstrapConfig.featureFlagPayloads`, such as `"123"`, as strings on iOS and macOS instead of decoding them to numbers or booleans
Expand Down
20 changes: 0 additions & 20 deletions api/posthog_flutter.api.json
Original file line number Diff line number Diff line change
Expand Up @@ -2554,15 +2554,6 @@
"relativePath": "lib/src/posthog_config.dart",
"typeName": "String"
},
{
"isDeprecated": false,
"isExperimental": false,
"isNamed": true,
"isRequired": false,
"name": "onFeatureFlags",
"relativePath": "lib/src/posthog_config.dart",
"typeName": "void Function(PostHogFeatureFlagsLoaded)?"
},
{
"isDeprecated": false,
"isExperimental": false,
Expand Down Expand Up @@ -2877,17 +2868,6 @@
"relativePath": "lib/src/posthog_config.dart",
"typeName": "PostHogBootstrapConfig?"
},
{
"entryPoints": [],
"isDeprecated": false,
"isExperimental": false,
"isReadable": true,
"isStatic": false,
"isWriteable": true,
"name": "onFeatureFlags",
"relativePath": "lib/src/posthog_config.dart",
"typeName": "void Function(PostHogFeatureFlagsLoaded)?"
},
{
"entryPoints": [],
"isDeprecated": false,
Expand Down
12 changes: 6 additions & 6 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,6 @@ Future<void> main() async {
final config = PostHogConfig(
'phc_6lqCaCDCBEWdIGieihq5R2dZpPVbAUFISA75vFZow06',
);
config.onFeatureFlags = (loaded) {
debugPrint(
'[PostHog] Feature flags loaded: ${loaded.variants}, '
'errorsLoading: ${loaded.errorsLoading}',
);
};

config.beforeSend = [
(event) {
Expand Down Expand Up @@ -84,6 +78,12 @@ Future<void> main() async {

Future<void> _initAndRun(PostHogConfig config) async {
WidgetsFlutterBinding.ensureInitialized();
Posthog().onFeatureFlags((loaded) {
debugPrint(
'[PostHog] Feature flags loaded: ${loaded.variants}, '
'errorsLoading: ${loaded.errorsLoading}',
);
});
await Posthog().setup(config);
runApp(const MyApp());
}
Expand Down
16 changes: 11 additions & 5 deletions posthog_flutter/MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,22 +213,28 @@ Future<void> disable() async {}
Future<void> optOut() async {}
```

### `onFeatureFlags` and `reloadFeatureFlags()`
### `PostHogConfig.onFeatureFlags` is removed
Comment thread
turnipdabeets marked this conversation as resolved.
Resolved

`PostHogConfig.onFeatureFlags` now receives a `PostHogFeatureFlagsLoaded`, and `reloadFeatureFlags()` returns a `Future<PostHogFeatureFlagsLoaded>`. It has `flags`, `variants` and `errorsLoading`.
Call `Posthog().onFeatureFlags()` before `setup()`, which also covers the first load. The callback receives a `PostHogFeatureFlagsLoaded`, with `flags`, `variants` and `errorsLoading`, and `reloadFeatureFlags()` now returns a `Future<PostHogFeatureFlagsLoaded>`.

```dart
// Before
final config = PostHogConfig('<project_token>', onFeatureFlags: () {
// ...
});
// or
config.onFeatureFlags = () {
// ...
};
await Posthog().setup(config);

// After
config.onFeatureFlags = (loaded) {
Posthog().onFeatureFlags((loaded) {
if (!loaded.errorsLoading) {
// Use loaded.variants
}
};
});
await Posthog().setup(config);
```

## Behavior changes
Expand Down Expand Up @@ -300,7 +306,7 @@ On web, `PostHogConfig.sendFeatureFlagEvent` is not applied to posthog-js, so an
- [ ] Rename `com.posthog.posthog.API_KEY` to `com.posthog.posthog.PROJECT_TOKEN` in `AndroidManifest.xml` and `Info.plist`.
- [ ] Use Xcode 26 or later.
- [ ] If you run your own reverse proxy or self-host, serve `/i/v1/analytics/events` and `/i/v1/ai/events` first.
- [ ] Update `onFeatureFlags` callbacks to take a `PostHogFeatureFlagsLoaded`.
- [ ] Replace `PostHogConfig.onFeatureFlags` with `Posthog().onFeatureFlags()` before `setup()`.
- [ ] Move anything that reads `version` or `build` on iOS and macOS lifecycle events to `$app_version` and `$app_build`.
- [ ] If you set `sendFeatureFlagEvent = false`, check whether anything relies on `$feature_flag_called` from `getFeatureFlagResult()`.
- [ ] Add `sendFeatureFlagEvent: false` wherever you replace `getFeatureFlagPayload()`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import com.posthog.PostHogBeforeSend
import com.posthog.PostHogBootstrapConfig
import com.posthog.PostHogCompression
import com.posthog.PostHogConfig
import com.posthog.PostHogFeatureFlagsCallback
import com.posthog.PostHogFeatureFlagsLoaded
import com.posthog.PostHogFeatureFlagsSubscription
import com.posthog.android.PostHogAndroid
import com.posthog.android.PostHogAndroidConfig
import com.posthog.android.internal.getApplicationInfo
Expand Down Expand Up @@ -168,6 +168,8 @@ class PosthogFlutterPlugin :

private var flutterSurveysDelegate: PostHogFlutterSurveysDelegate? = null

private var featureFlagsSubscription: PostHogFeatureFlagsSubscription? = null

override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
if (bitmapExportExecutor.isShutdown) {
bitmapExportExecutor = Executors.newSingleThreadExecutor()
Expand All @@ -178,6 +180,16 @@ class PosthogFlutterPlugin :
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "posthog_flutter")

this.applicationContext = flutterPluginBinding.applicationContext
// Before initPlugin, so this also catches the first load of a native auto-init.
featureFlagsSubscription?.unsubscribe()
featureFlagsSubscription =
PostHog.onFeatureFlags { loaded ->
Log.i("PostHogFlutter", "Android onFeatureFlags triggered. Notifying Dart.")
invokeFlutterMethod(
"onFeatureFlagsCallback",
loaded.toFlutterMap() + ("generation" to flagsGeneration),
)
}
initPlugin()

channel.setMethodCallHandler(this)
Expand Down Expand Up @@ -850,15 +862,6 @@ class PosthogFlutterPlugin :
)
}
}

onFeatureFlags =
PostHogFeatureFlagsCallback { loaded ->
Log.i("PostHogFlutter", "Android onFeatureFlags triggered. Notifying Dart.")
invokeFlutterMethod(
"onFeatureFlagsCallback",
loaded.toFlutterMap() + ("generation" to flagsGeneration),
)
}
}

lastBuiltConfig = config
Expand Down Expand Up @@ -999,6 +1002,8 @@ class PosthogFlutterPlugin :

override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
stopOcclusionDetector()
featureFlagsSubscription?.unsubscribe()
featureFlagsSubscription = null
channel.setMethodCallHandler(null)
pushChannelCandidates.remove(channel)
if (activeChannel === channel) {
Expand Down
7 changes: 1 addition & 6 deletions posthog_flutter/lib/posthog_flutter_web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {

// Skipped for a posthog-js stub without onFeatureFlags.
if (ph != null && (ph as JSObject).has('onFeatureFlags')) {
final dartCallback = config.onFeatureFlags;
// Repeated setup would otherwise deliver each load twice.
_featureFlagsUnsubscribe?.callAsFunction();
_featureFlagsUnsubscribe = null;
Expand All @@ -167,11 +166,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface {
'variants': jsFlagVariants.dartify(),
'errorsLoading': (jsContext?.dartify() as Map?)?['errorsLoading'],
});
// First, so a throwing config callback can't starve listeners and a
// reset() or close() it starts clears this load.
if (FeatureFlagsListeners.instance.deliver(loaded)) {
dartCallback?.call(loaded);
}
FeatureFlagsListeners.instance.deliver(loaded);
}.toJS;

// posthog-js replays loaded flags synchronously, and a callback may call
Expand Down
8 changes: 3 additions & 5 deletions posthog_flutter/lib/src/feature_flags_listeners.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,15 @@ class FeatureFlagsListeners {
return PostHogFeatureFlagsSubscription(() => _listeners.remove(token));
}

/// Returns false when a listener's `reset()` or `close()` cleared [loaded]
/// mid-delivery, so the caller skips the config callback too.
bool deliver(PostHogFeatureFlagsLoaded loaded) {
void deliver(PostHogFeatureFlagsLoaded loaded) {
_last = loaded;
final generation = _generation;
for (final entry in _listeners.entries.toList()) {
if (generation != _generation) return false;
// A listener's reset() or close() cleared this load.
if (generation != _generation) return;
// An earlier listener may have unsubscribed this one.
if (_listeners.containsKey(entry.key)) _notify(entry.value, loaded);
}
return generation == _generation;
}

// A throwing listener must not stop the others from getting the load.
Expand Down
26 changes: 12 additions & 14 deletions posthog_flutter/lib/src/feature_flags_loaded.dart
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import 'package:meta/meta.dart';

/// The feature flags passed to [PostHogConfig.onFeatureFlags] and returned by
/// [Posthog.reloadFeatureFlags].
/// The feature flags passed to [Posthog.onFeatureFlags] listeners and returned
/// by [Posthog.reloadFeatureFlags].
///
/// Only enabled flags are included. When the latest load failed,
/// [errorsLoading] is `true` and the flags are the last known values, which
/// can be empty.
///
/// **Example:**
/// ```dart
/// final config = PostHogConfig('<project_token>')
/// ..onFeatureFlags = (loaded) {
/// if (loaded.errorsLoading) {
/// // The values are the last known (cached) flags.
/// }
/// if (loaded.variants['new-checkout'] == 'test') {
/// // Show the test variant.
/// }
/// };
/// Posthog().onFeatureFlags((loaded) {
/// if (loaded.errorsLoading) {
/// // The values are the last known (cached) flags.
/// }
/// if (loaded.variants['new-checkout'] == 'test') {
/// // Show the test variant.
/// }
/// });
/// ```
class PostHogFeatureFlagsLoaded {
/// The keys of the enabled feature flags.
Expand All @@ -33,9 +32,8 @@ class PostHogFeatureFlagsLoaded {
///
/// When it did, [flags] and [variants] hold the last known values.
///
/// **Flutter web:** when [PostHogConfig.onFeatureFlags] is first set, it is
/// called right away with the current flags and `false`, even if
/// posthog-js's last load before that failed.
/// **Flutter web:** the first load after [Posthog.setup] can be the current
/// flags with `false`, even if posthog-js's last load before that failed.
final bool errorsLoading;

/// Creates the loaded feature flags from [variants], keeping only enabled
Expand Down
8 changes: 4 additions & 4 deletions posthog_flutter/lib/src/posthog.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ class Posthog {
/// the SDK for tracking events and feature flags.
///
/// The [config] object contains your project token, host, and other settings.
/// To listen for feature flag load events, provide an `onFeatureFlags`
/// callback in the [PostHogConfig].
/// To listen for feature flag load events, call [onFeatureFlags] before this
/// method.
///
/// Repeated setup reapplies Dart-side settings such as the error-tracking
/// hooks. Most native settings still require [close] before setup because
Expand All @@ -59,9 +59,9 @@ class Posthog {
/// ```dart
/// final config = PostHogConfig('YOUR_PROJECT_TOKEN');
/// config.host = 'YOUR_POSTHOG_HOST';
/// config.onFeatureFlags = (loaded) {
/// Posthog().onFeatureFlags((loaded) {
/// // Feature flags are now loaded, you can read flag values here
/// };
/// });
/// await Posthog().setup(config);
/// ```
///
Expand Down
26 changes: 0 additions & 26 deletions posthog_flutter/lib/src/posthog_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -311,28 +311,6 @@ class PostHogConfig {
/// call instead.
PostHogBootstrapConfig? bootstrap;

/// Callback to be invoked when feature flags are loaded.
///
/// It receives the enabled flags and whether loading failed. It runs after
/// the flags load at startup, after [Posthog.reloadFeatureFlags], and after
/// calls that reload flags such as `identify()` or `group()`. When a load
/// fails, [PostHogFeatureFlagsLoaded.errorsLoading] is `true` and the flags
/// are the last known values. Defaults to `null`.
///
/// **Android:** not called after [Posthog.reloadFeatureFlags]. Use the
/// flags that call returns instead.
///
/// **Example:**
/// ```dart
/// final config = PostHogConfig('<project_token>')
/// ..onFeatureFlags = (loaded) {
/// if (loaded.variants['new-checkout'] == 'test') {
/// // Show the test variant.
/// }
/// };
/// ```
OnFeatureFlagsCallback? onFeatureFlags;

/// Whether to automatically register this device's push token or Firebase
/// Installation ID (FID) with PostHog.
///
Expand Down Expand Up @@ -460,14 +438,10 @@ class PostHogConfig {
///
/// The [projectToken] is trimmed before it is stored.
///
/// The optional [onFeatureFlags] callback is invoked when feature flags finish
/// loading.
///
/// The optional [beforeSend] callbacks are copied into [beforeSend] and run in
/// order before Dart-captured events are sent.
PostHogConfig(
String projectToken, {
this.onFeatureFlags,
List<BeforeSendCallback>? beforeSend,
}) : projectToken = projectToken.trim(),
beforeSend = beforeSend ?? [];
Expand Down
8 changes: 2 additions & 6 deletions posthog_flutter/lib/src/posthog_flutter_desktop.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
_ClientScope? _clientScope;

/// The configuration of the latest setup(), read by the Dart-side hooks:
/// beforeSend, onFeatureFlags and exception processing.
/// beforeSend and exception processing.
PostHogConfig? _config;

void Function()? _featureFlagsUnsubscribe;
Expand Down Expand Up @@ -180,11 +180,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface {
);
_featureFlagsUnsubscribe = client.onFeatureFlags(() {
final loaded = client.featureFlagsLoaded();
// First, so a throwing config callback can't starve listeners and a
// reset() or close() it starts clears this load.
if (FeatureFlagsListeners.instance.deliver(loaded)) {
_config?.onFeatureFlags?.call(loaded);
}
FeatureFlagsListeners.instance.deliver(loaded);
});

final stepsConfig = config.errorTrackingConfig.exceptionSteps;
Expand Down
22 changes: 3 additions & 19 deletions posthog_flutter/lib/src/posthog_flutter_io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface {
bool _handlerInstalled = false;
Timer? _handlerRetry;

OnFeatureFlagsCallback? _onFeatureFlagsCallback;

PushIdentityProvider? _pushIdentityProvider;

/// Stored configuration for accessing inAppIncludes and other settings
Expand Down Expand Up @@ -132,12 +130,8 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface {
FeatureFlagsListeners.instance.generation) {
break;
}
final loaded = featureFlagsLoadedFromMap(call.arguments);
// First, so a throwing config callback can't starve listeners and a
// reset() or close() it starts clears this load.
if (FeatureFlagsListeners.instance.deliver(loaded)) {
_onFeatureFlagsCallback?.call(loaded);
}
FeatureFlagsListeners.instance
.deliver(featureFlagsLoadedFromMap(call.arguments));
break;
case 'pushIdentityProvider':
// Returning a value here is the reply the native SDK awaits.
Expand Down Expand Up @@ -268,7 +262,6 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface {
return;
}

_onFeatureFlagsCallback = config.onFeatureFlags;
_pushIdentityProvider = config.pushIdentityProvider;
_beforeSendCallbacks = config.beforeSend;

Expand Down Expand Up @@ -751,17 +744,8 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface {
return featureFlagsLoadedFromMap(null);
}

final generation = FeatureFlagsListeners.instance.generation;
try {
final loaded =
featureFlagsLoadedFromMap(await _invoke('reloadFeatureFlags'));
// posthog-android hands a manual reload only to its completion, not to
// the config callback that sends onFeatureFlagsCallback.
if (defaultTargetPlatform == TargetPlatform.android &&
generation == FeatureFlagsListeners.instance.generation) {
FeatureFlagsListeners.instance.deliver(loaded);
}
return loaded;
return featureFlagsLoadedFromMap(await _invoke('reloadFeatureFlags'));
} on PlatformException catch (exception) {
printIfDebug('Exeption on reloadFeatureFlags: $exception');
return featureFlagsLoadedFromMap(null);
Expand Down
Loading
Loading