Skip to main content

User Identification

The SDK provides a setUser() method to associate analytics events with a known user. Once called, B2Metric links all subsequent events from that device to the user's profile in the dashboard, enabling per-user analytics, cohort analysis, and personalised campaign targeting.

Identify a User

Call setUser() once the user's identity is known — typically after login or session restore. Pass a B2MetricUser object; userId is required, all other fields are optional.

B2Metric.instance.setUser(B2MetricUser(
userId: 'user_123',
name: 'Ahmet',
email: 'ahmet@example.com',
properties: {'plan': 'premium'}, // any custom attributes
));

What setUser Does

Calling setUser() performs two operations simultaneously:

  1. Sends a user_identify event that creates or updates the user's profile attributes in the B2Metric dashboard.
  2. Merges the supplied attributes into the user_properties of every subsequent event, making them available for event-level filtering and segmentation.
Note

The user_properties attached to each event is a point-in-time snapshot taken when the event is tracked. Calling setUser later does not retroactively update already-queued events. If a user attribute changes (for example, a plan upgrade), call setUser again with the new values.

Supported Fields

userId (String, required) — Your application's identifier for the user. Choose a stable value such as a database primary key or UUID. Do not use email addresses as the primary identifier since they can change.

name (String, optional) — The user's display name or first name.

surname (String, optional) — The user's surname or family name.

email (String, optional) — The user's email address.

properties (Map<String, dynamic>, optional) — Any additional custom attributes. Values follow the same type rules as event properties: String, num, bool, DateTime, null, plain maps, and lists are all valid.

Device Fields Cannot Be Overridden

If a key in properties matches a device field collected automatically (for example device_id or os_version), the device value always takes precedence.

Persistence Across App Launches

User attributes are not persisted to disk between app launches. Call setUser() again each time the app starts, once the user's identity is available. A common pattern is to chain it inside the main() function after init() resolves:

await B2Metric.instance.init(
const B2MetricConfig(
apiKey: 'YOUR_API_KEY',
appIdentifier: 'YOUR_APP_IDENTIFIER',
),
);

if (currentUser != null) {
B2Metric.instance.setUser(B2MetricUser(
userId: currentUser.id,
email: currentUser.email,
));
}