SDK Public API
class AltcraftSDK
The entry point to the SDK. All methods are static. JWT and push token provider are registered natively (Application.onCreate on Android, AppDelegate on iOS) and are not accessible via the Dart API.
AltcraftSDK
// ---- Initialization ----
├─ static Future<void> initialize(AltcraftConfig config)
├─ static Future<void> clear()
├─ static Future<bool> requestNotificationPermission()
└─ static void unlockInitialOperationsInThisSession()
// ---- Push Subscription ----
├─ static void pushSubscribe({bool? sync, ...})
├─ static void pushSuspend({bool? sync, ...})
├─ static void pushUnSubscribe({bool? sync, ...})
└─ static Future<ResponseWithHttpCode?> unSuspendPushSubscription()
// ---- Subscription Status ----
├─ static Future<ResponseWithHttpCode?> getStatusOfLatestSubscription()
├─ static Future<ResponseWithHttpCode?> getStatusForCurrentSubscription()
└─ static Future<ResponseWithHttpCode?> getStatusOfLatestSubscriptionForProvider(String? provider)
// ---- SDK Events ----
├─ static Stream<SdkEvent> subscribeToEvents()
└─ static Future<void> unsubscribeFromEvents()
// ---- Mobile Events and Profile ----
├─ static void mobileEvent({required String sid, required String eventName, ...})
└─ static void updateProfileFields({Map<String, dynamic>? profileFields, bool? skipTriggers})
// ---- Push Tokens ----
├─ static Future<TokenData?> getPushToken()
├─ static Future<void> setPushToken(String provider, String? token)
├─ static Future<void> forcedTokenUpdate()
├─ static Future<void> deleteDeviceToken(String provider)
└─ static Future<void> changePushProviderPriorityList(List<String> priorityList)
// ---- Push Notifications (Android) ----
├─ static void takePush(Map<String, String> message)
├─ static Future<bool> isAltcraftPush(Map<String, String> message)
├─ static void deliveryEvent(Map<String, String>? message, String? messageUID)
└─ static void openEvent(Map<String, String>? message, String? messageUID)
// ---- Native storage (iOS / Android) ----
├─ static void setAppGroup(String? groupName)
└─ static void setUserDefaultsValue(String? suiteName, String key, dynamic value)
Initialization
initialize(config)
static Future<void> initialize(AltcraftConfig config)
Initializes the Altcraft SDK with the given configuration. Called once at application startup, before runApp().
| Parameter | Type | Description |
|---|---|---|
config | AltcraftConfig | SDK configuration object (required). |
Returns: Future<void> — completes when the native SDK has finished initialization.
Throws: AltcraftException on initialization error on the native side.
import 'package:altcraft_sdk/altcraft_sdk.dart';
import 'package:flutter/widgets.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await AltcraftSDK.initialize(
AltcraftConfig(
apiUrl: 'https://pxl-example.altcraft.com',
appInfo: const AppInfo(
appID: '1:000000000000:android:0000000000000000',
appIID: '00000000-0000-4000-8000-000000000000',
appVer: '1.0.0',
),
providerPriorityList: ['android-firebase'],
),
);
runApp(const MyApp());
}
clear()
static Future<void> clear()
Complete SDK data cleanup: local database, token storage, cancellation of all background tasks.
Returns: Future<void>. Throws: AltcraftException on error.
requestNotificationPermission()
static Future<bool> requestNotificationPermission()
Requests notification permission (Android 13+). On iOS, permissions are configured natively.
Returns: Future<bool> — true if permission is granted, false if denied.
final bool granted = await AltcraftSDK.requestNotificationPermission();
if (granted) {
AltcraftSDK.pushSubscribe(sync: true);
}
unlockInitialOperationsInThisSession()
static void unlockInitialOperationsInThisSession()
Allows re-initialization of the push module in the current session (Android). Used when push components need to be re-initialized without restarting the application.
Push Subscription
pushSubscribe() / pushSuspend() / pushUnSubscribe()
static void pushSubscribe({
bool? sync,
Map<String, dynamic>? profileFields,
Map<String, dynamic>? customFields,
List<dynamic>? cats,
bool? replace,
bool? skipTriggers,
})
static void pushSuspend({...})
static void pushUnSubscribe({...})
| Method | Status | Event codes |
|---|---|---|
pushSubscribe() | subscribed | 230 (success), 430 (error), 530 (retry) |
pushSuspend() | suspended | 231 (success), 431 (error), 531 (retry) |
pushUnSubscribe() | unsubscribed | 232 (success), 432 (error), 532 (retry) |
All three methods have the same signature.
| Parameter | Type | Description |
|---|---|---|
sync | bool? | true — synchronous request (result via SDK event). false — asynchronous. |
profileFields | Map<String, dynamic>? | Profile fields (system and optional). |
customFields | Map<String, dynamic>? | Custom subscription fields (scalars only). |
cats | List<dynamic>? | Subscription categories (name + active). |
replace | bool? | When true, subscriptions of other profiles with the same push token are set to unsubscribed. |
skipTriggers | bool? | When true, the profile is ignored in mailing and scenario triggers. |
Returns: void (fire-and-forget). Result is available via SDK events.
AltcraftSDK.pushSubscribe(
sync: true,
profileFields: const {'_fname': 'Ivan', '_lname': 'Petrov'},
cats: const [{'name': 'news', 'active': true}],
);
unSuspendPushSubscription()
static Future<ResponseWithHttpCode?> unSuspendPushSubscription()
Resumes a suspended subscription. Used for LogIn/LogOut transitions between profiles.
Algorithm:
- Searches for subscriptions with the same push token not belonging to the current JWT's profile;
- Changes their status from
subscribedtosuspended; - Changes the status of the current JWT profile's subscriptions from
suspendedtosubscribed; - Returns the current JWT profile data (or
nullif the profile is not found).
Returns: Future<ResponseWithHttpCode?> — profile data or null.
final ResponseWithHttpCode? result =
await AltcraftSDK.unSuspendPushSubscription();
if (result == null) {
AltcraftSDK.pushSubscribe();
}
Subscription Status
getStatusOfLatestSubscription()
static Future<ResponseWithHttpCode?> getStatusOfLatestSubscription()
Returns the status of the latest profile subscription. response?.profile?.subscription contains the last created subscription. If no subscriptions exist — null.
getStatusForCurrentSubscription()
static Future<ResponseWithHttpCode?> getStatusForCurrentSubscription()
Returns the subscription status for the current push token and provider. response?.profile?.subscription contains the subscription found by the current token. If no subscription exists — null.
getStatusOfLatestSubscriptionForProvider(provider)
static Future<ResponseWithHttpCode?> getStatusOfLatestSubscriptionForProvider(
String? provider,
)
Returns the status of the latest subscription for the specified provider. If provider = null, the current token's provider is used.
| Parameter | Type | Description |
|---|---|---|
provider | String? | Provider identifier (e.g., android-firebase). |
All three methods return Future<ResponseWithHttpCode?> and throw AltcraftException on error.
SDK Events
subscribeToEvents()
static Stream<SdkEvent> subscribeToEvents()
Returns a stream of SDK events. Events are delivered from the native SDK via EventChannel (com.altcraft/events). Each call creates an independent Stream.
Returns: Stream<SdkEvent>.
unsubscribeFromEvents()
static Future<void> unsubscribeFromEvents()
Stops event delivery from the native SDK. To re-subscribe, call subscribeToEvents().
Returns: Future<void>.
import 'dart:async';
import 'package:altcraft_sdk/altcraft_sdk.dart';
StreamSubscription<SdkEvent>? subscription;
void startListening() {
subscription = AltcraftSDK.subscribeToEvents().listen(
(SdkEvent event) {
print('[${event.type}] ${event.function}: ${event.message}');
},
);
}
Future<void> stopListening() async {
await subscription?.cancel();
subscription = null;
await AltcraftSDK.unsubscribeFromEvents();
}
Mobile Events and Profile
mobileEvent()
static void mobileEvent({
required String sid,
required String eventName,
String? sendMessageId,
Map<String, dynamic>? payload,
Map<String, dynamic>? matching,
String? matchingType,
Map<String, dynamic>? profileFields,
Map<String, dynamic>? subscription,
Map<String, dynamic>? utm,
})
Registers an Altcraft mobile event.
| Parameter | Type | Description |
|---|---|---|
sid | String | Pixel identifier (required). |
eventName | String | Event name (required). |
sendMessageId | String? | SMID of the sent message. |
payload | Map<String, dynamic>? | Event data. Serialized via MethodChannel. |
matching | Map<String, dynamic>? | Matching data (e.g., {'email': 'user@example.com'}). |
matchingType | String? | Matching type. |
profileFields | Map<String, dynamic>? | Profile fields (JWT scenarios). |
subscription | Map<String, dynamic>? | Subscription for a channel. Use Subscription.toMap(). |
utm | Map<String, dynamic>? | UTM tags. |
Returns: void.
AltcraftSDK.mobileEvent(
sid: 'pixel-000000000000000000000000',
eventName: 'purchase',
payload: const {
'orderId': 'A-1001',
'amount': 3990,
'currency': 'RUB',
},
);
updateProfileFields()
static void updateProfileFields({
Map<String, dynamic>? profileFields,
bool? skipTriggers,
})
Updates profile fields on the server.
| Parameter | Type | Description |
|---|---|---|
profileFields | Map<String, dynamic>? | Map of profile fields to update. |
skipTriggers | bool? | When true, the profile is ignored in mailing and scenario triggers. |
Returns: void.
Push Tokens
getPushToken()
static Future<TokenData?> getPushToken()
Returns the current device push token and provider data.
Returns: Future<TokenData?> — TokenData object or null if the token is unavailable.
Throws: AltcraftException on error.
setPushToken(provider, token)
static Future<void> setPushToken(String provider, String? token)
Sets or clears the push token for the specified provider. Storage is performed on the native SDK side.
| Parameter | Type | Description |
|---|---|---|
provider | String | Provider identifier (e.g., android-firebase, ios-apns). |
token | String? | Token value. null — clears the token. |
forcedTokenUpdate()
static Future<void> forcedTokenUpdate()
Forced push token update: deletes the current token and requests a new one from the provider.
deleteDeviceToken(provider)
static Future<void> deleteDeviceToken(String provider)
Deletes the device token for the specified provider.
| Parameter | Type | Description |
|---|---|---|
provider | String | Provider identifier. |
changePushProviderPriorityList(priorityList)
static Future<void> changePushProviderPriorityList(List<String> priorityList)
Changes the push provider priority list and initiates a token update.
| Parameter | Type | Description |
|---|---|---|
priorityList | List<String> | New priority list. Index 0 is the highest priority. |
await AltcraftSDK.changePushProviderPriorityList(
['android-firebase', 'android-huawei', 'android-rustore'],
);
All methods throw AltcraftException on error.
Push Notifications (Android)
takePush(message)
static void takePush(Map<String, String> message)
Passes incoming push payload to the SDK. Works on Android. On iOS, push processing is handled natively.
| Parameter | Type | Description |
|---|---|---|
message | Map<String, String> | Push notification data converted to Map<String, String>. |
isAltcraftPush(message)
static Future<bool> isAltcraftPush(Map<String, String> message)
Checks whether a push message belongs to Altcraft.
| Parameter | Type | Description |
|---|---|---|
message | Map<String, String> | Push message payload. |
Returns: Future<bool> — true if the message belongs to Altcraft.
deliveryEvent(message, messageUID)
static void deliveryEvent(Map<String, String>? message, String? messageUID)
Manual push notification delivery registration (Android).
| Parameter | Type | Description |
|---|---|---|
message | Map<String, String>? | Notification data payload. |
messageUID | String? | Message identifier. |
You can pass only message (SDK will extract the UID from the payload) or only messageUID. If both are null, the event will not be registered.
openEvent(message, messageUID)
static void openEvent(Map<String, String>? message, String? messageUID)
Manual push notification opening registration (Android). Parameters and passing rules are identical to deliveryEvent().
Native storage (iOS / Android)
setAppGroup(groupName)
static void setAppGroup(String? groupName)
Sets the App Group for UserDefaults on iOS. Defines the space shared between the main application and the Notification Service Extension.
| Parameter | Type | Description |
|---|---|---|
groupName | String? | App Group identifier (e.g., group.altcraft.example). |
setUserDefaultsValue(suiteName, key, value)
static void setUserDefaultsValue(String? suiteName, String key, dynamic value)
Saves a value to native storage: UserDefaults on iOS, SharedPreferences on Android. The value is converted to a string via toString().
| Parameter | Type | Description |
|---|---|---|
suiteName | String? | App Group / suite name (iOS). Ignored on Android. |
key | String | Storage key. |
value | dynamic | Value (converted to String). |
class AltcraftConfig
class AltcraftConfig {
final String apiUrl;
final String? rToken;
final AppInfo? appInfo;
final List<String>? providerPriorityList;
final bool? enableLogging;
// -------- ANDROID-ONLY --------
final int? icon;
final List<String>? pushReceiverModules;
final String? pushChannelName;
final String? pushChannelDescription;
}
Altcraft SDK configuration class. Stores the base API URL and optional parameters.
| Field | Type | Required | Description |
|---|---|---|---|
apiUrl | String | Yes | Base Altcraft API URL. |
rToken | String? | No | Role token (identifies resource/DB/account). |
appInfo | AppInfo? | No | Application metadata (ID, IID, version). |
providerPriorityList | List<String>? | No | Push provider priority. Index 0 is the highest priority. |
enableLogging | bool? | No | Enables/disables logging. |
icon | int? | No | Notification icon resource ID (Android). |
pushReceiverModules | List<String>? | No | Packages of modules with overridden PushReceiver (Android). |
pushChannelName | String? | No | Push notification channel name (Android). |
pushChannelDescription | String? | No | Push notification channel description (Android). |
AppInfo:
class AppInfo {
final String appID;
final String appIID;
final String appVer;
}
| Field | Type | Description |
|---|---|---|
appID | String | Application identifier (Firebase App ID). |
appIID | String | Installation identifier (Firebase Instance ID). |
appVer | String | Application version. |
Data Classes
SdkEvent
class SdkEvent {
final String function;
final int? code;
final String message;
final String type;
final Map<String, dynamic>? value;
final String? timestamp;
}
Universal SDK event, delivered to Dart via Stream (uses EventChannel under the hood).
| Field | Type | Description |
|---|---|---|
function | String | Name of the SDK function that triggered the event. |
code | int? | Event code (see code table). |
message | String | Event message. |
type | String | event, error, retryError. |
value | Map<String, dynamic>? | Additional data (e.g., response_with_http_code). |
timestamp | String? | Timestamp in yyyy-MM-dd HH:mm:ss.SSS format. |
TokenData
class TokenData {
final String provider;
final String token;
}
Device provider push token data.
| Field | Type | Description |
|---|---|---|
provider | String | Provider identifier (e.g., android-firebase, ios-apns). |
token | String | Push token value. |
ResponseWithHttpCode
class ResponseWithHttpCode {
final int httpCode;
final Map<String, dynamic>? response;
}
API response wrapper with HTTP code. The response field contains:
| Field | Type | Description |
|---|---|---|
error | int? | Internal server error code (0 — no errors). |
errorText | String? | Error text. |
profile | Map<String, dynamic>? | Profile and subscription data. |
Nested profile structure:
| Field | Type | Description |
|---|---|---|
id | String? | Profile identifier. |
status | String? | Profile status. |
isTest | bool? | Test mode flag. |
subscription | Map<String, dynamic>? | Subscription data. |
Nested subscription structure:
| Field | Type | Description |
|---|---|---|
subscription_id | String? | Subscription identifier at the provider. |
hash_id | String? | Subscription hash. |
provider | String? | Subscription provider. |
status | String? | Subscription status (subscribed, suspended, unsubscribed). |
fields | Map<String, dynamic>? | System and custom fields. |
cats | List<dynamic>? | Subscription categories. |
CategoryData
class CategoryData {
final String? name;
final String? title;
final bool? steady;
final bool? active;
}
Subscription category.
| Field | Type | Description |
|---|---|---|
name | String? | Category name. |
title | String? | Title (populated when retrieving subscription data). |
steady | bool? | Stability flag (populated when retrieving subscription data). |
active | bool? | Category active status. |
When sending a push request, only use name and active.
Subscription
class Subscription {
final String type;
final int resourceId;
final String? status;
final int? priority;
final String? email;
final String? phone;
final String? provider;
final String? subscriptionId;
final Map<String, dynamic>? customFields;
final List<dynamic>? cats;
final Map<String, dynamic>? ccData;
}
Subscription model for mobile events. Factory constructors:
// Email
Subscription.email({required int resourceId, required String email, ...})
// SMS
Subscription.sms({required int resourceId, required String phone, ...})
// Push
Subscription.push({required int resourceId, required String provider, required String subscriptionId, ...})
// CcData (Telegram, WhatsApp, Viber, Notify)
Subscription(type: 'cc_data', resourceId: 10, ccData: {'channel': 'telegram_bot', 'chat_id': '123456'})
The toMap() method serializes the subscription to Map<String, dynamic> for passing to mobileEvent().
UTM
class UTM {
final String? source;
final String? medium;
final String? campaign;
final String? content;
final String? keyword;
final String? temp;
}
UTM parameter container for mobile event attribution. Passed to mobileEvent() as Map<String, dynamic>.
ActionFieldBuilder
class ActionFieldBuilder {
final String key;
Map<String, dynamic> set(dynamic value);
Map<String, dynamic> unset(dynamic value);
Map<String, dynamic> incr(dynamic value);
Map<String, dynamic> add(dynamic value);
Map<String, dynamic> delete(dynamic value);
Map<String, dynamic> upsert(dynamic value);
}
ActionFieldBuilder actionField(String key);
Builder for structured profile field management. Produces a map compatible with the native SDK.
| Method | Description |
|---|---|
set(value) | Set the field to the given value. |
unset(value) | Remove the field value. |
incr(value) | Increment a numeric field by the given value. |
add(value) | Add a value to a set/array field. |
delete(value) | Remove a value from a set/array field. |
upsert(value) | Set if the field is missing; update if it exists. |
import 'package:altcraft_sdk/altcraft_sdk.dart';
final profileFields = <String, dynamic>{
...actionField('_fname').set('Ivan'),
...actionField('login_count').incr(1),
...actionField('visited_pages').add('/settings'),
};
AltcraftSDK.updateProfileFields(profileFields: profileFields);
Exceptions
AltcraftException
class AltcraftException implements Exception {
final String code;
final String message;
final Object? details;
}
Exception thrown by the SDK on method call errors via MethodChannel.
| Field | Type | Description |
|---|---|---|
code | String | Error code. |
message | String | Error message. |
details | Object? | Additional data. |
SdkNotInitializedException
class SdkNotInitializedException extends AltcraftException
Thrown when SDK methods are called before initialization. Code: SDK_NOT_INITIALIZED.
try {
await AltcraftSDK.getStatusOfLatestSubscription();
} on SdkNotInitializedException {
print('SDK not initialized yet');
} on AltcraftException catch (e) {
print('SDK error (${e.code}): ${e.message}');
}
Constants
Push notification providers:
| Provider | Value |
|---|---|
| FCM (Android) | android-firebase |
| HMS (Android) | android-huawei |
| RuStore (Android) | android-rustore |
| APNS (iOS) | ios-apns |
| FCM (iOS) | ios-firebase |
| HMS (iOS) | ios-huawei |
Subscription statuses:
| Status | Value |
|---|---|
| Subscribed | subscribed |
| Unsubscribed | unsubscribed |
| Suspended | suspended |