Sense Flutter SDK

Sense provides device intelligence and device security signals for Flutter applications.

Installation

Add the SDK to your app's pubspec.yaml:

dependencies:
  sense_flutter_plugin: ^2.0.4

Import the SDK in Dart:

import 'package:sense_flutter_plugin/sense_flutter_plugin.dart';

Initialize the SDK

Create a Sense instance and initialize it before requesting device details. A good place to do this is a StatefulWidget's initState method.

final Sense sense = Sense();

@override
void initState() {
  super.initState();
  _initializeSense();
}

Future<void> _initializeSense() async {
  await sense.initSDK({
    "publicKey": "YOUR_PUBLIC_KEY",
    "senseInfo": true,
    "allowGeoLocation": false,
    "tag": "YOUR_APP_NAME",
    "sessionId": "", // Optional workflow/session identifier.
    "metaInfo": {
      "phone": "USER_PHONE",
      "name": "USER_NAME",
    },
    "optional": <String, dynamic>{},
    "expectedAppSignatures": <String>[],
    "expectedPackageName": "com.example.your_app",
    "sslPinningConfig": {
      "enabled": true,
      "pinSets": [
        {
          "host": "api.example.com",
          "pins": [
            "sha256/YOUR_BASE64_SPKI_HASH=",
            "sha256/YOUR_BACKUP_BASE64_SPKI_HASH=",
          ],
        },
      ],
    },
    "senseLogConfig": {
      "enable": false,
    },
  });
}

Replace the placeholder values with values from your Sense client configuration. The public key is required. metaInfo is optional and supports up to 15 key-value pairs; each key and value can contain up to 256 characters.

Configuration arguments

Argument Description
publicKey Sense public API key. Required.
senseInfo Enables Sense information in the response.
allowGeoLocation Allows location-related signals when supported and permitted by the platform.
tag Application or integration label.
sessionId Optional identifier used for workflow integrations.
metaInfo Additional application-provided key-value data.
optional Additional SDK-specific options.
expectedAppSignatures Expected Android app signatures for integrity validation.
expectedPackageName Expected Android application package name.
sslPinningConfig Certificate pinning configuration for specific hosts.
senseLogConfig SDK logging configuration. Keep logging disabled in production unless needed.

SSL pinning

Set sslPinningConfig.enabled to true only when every configured host has valid, current pins. Each pinSets entry contains an exact hostname and one or more SHA-256 public-key pins. Multiple pins allow a backup certificate during certificate rotation.

For application requests, use pinnedRequest after awaiting initSDK. It uses Sense.setSSLPinning() on Android and Sense.makePinnedURLSession() on iOS. Ordinary http, Dio, and dart:io clients do not inherit these pins.

final response = await sense.pinnedRequest(
  Uri.parse('https://api.example.com/v1/profile'),
  headers: {'Authorization': 'Bearer YOUR_TOKEN'},
);
if (response.statusCode == 200) {
  final profile = jsonDecode(response.body);
}

pinnedRequest requires HTTPS and an explicit pin set for the URL host. It returns the status code, response headers, and bodyBytes; body decodes UTF-8 text. For POST/PUT/PATCH, pass UTF-8 encoded or binary request bytes via body. Android returns 3xx responses without following redirects. The iOS pinned session requires pins for any redirected HTTPS host. A missing pin, failed TLS validation, or SDK pin initialization failure throws a PlatformException. This API buffers the full request and response in memory; use the native pinned clients directly for streaming or large downloads.

Dio with application pinning

  1. Add Dio to your application's pubspec.yaml alongside sense_flutter_plugin, then run flutter pub get:

    dependencies:
      sense_flutter_plugin: ^2.0.4
      dio: ^5.0.0
    
  2. Configure the exact HTTPS host and its current SHA-256 public-key pins, then await initSDK before sending requests. Replace the example host, key, and pin with your own values:

    import 'package:dio/dio.dart';
    import 'package:sense_flutter_plugin/sense_flutter_plugin.dart';
    
    final sense = Sense();
    await sense.initSDK({
      'publicKey': 'YOUR_PUBLIC_KEY',
      'sslPinningConfig': {
        'enabled': true,
        'pinSets': [
          {'host': 'api.example.com', 'pins': ['sha256/YOUR_BASE64_SPKI_HASH=']},
        ],
      },
    });
    
  3. Create a Dio instance that uses the Sense-pinned native transport:

    final dio = sense.createPinnedDio(
      options: BaseOptions(baseUrl: 'https://api.example.com'),
    );
    
  4. Send requests through that instance and handle failures as Dio errors:

    try {
      final response = await dio.get('/v1/profile');
      print(response.data);
    } on DioException catch (error) {
      // Includes pinning, TLS, network, and HTTP-status failures.
      print('Request failed: $error');
    } finally {
      dio.close();
    }
    

If you already create a Dio instance elsewhere, install the adapter before its first request instead of calling createPinnedDio():

final dio = Dio(BaseOptions(baseUrl: 'https://api.example.com'));
dio.httpClientAdapter = SensePinnedDioAdapter(sense);

Only requests through the configured Dio instance use Sense pinning; ordinary Dio clients do not inherit it. The adapter supports standard request methods, headers, Dio-encoded bodies, interceptors, and response decoding. It buffers complete request and response bodies; Dio cancellation cannot stop an in-flight native request, and live streaming and Dio's per-request timeout settings are not mapped to the native transport. On Android, redirects return as 3xx responses even when Dio's followRedirects is true. This transport works on Android and iOS only.

When a certificate or public key changes, update the pins before deploying the server certificate change. Incorrect or expired pins can block requests to the configured host.

Use an empty configuration when pinning is not required:

"sslPinningConfig": {
  "enabled": false,
  "pinSets": <Map<String, dynamic>>[],
},

Get device details

getSenseDetails() returns a response map containing success, message, and, on success, data.

Future<void> getDeviceDetails() async {
  final response = await sense.getSenseDetails();

  if (response is! Map || response["success"] != true) {
    final message = response is Map
        ? response["message"]?.toString() ?? "Unable to get device details"
        : "Invalid SDK response";
    throw StateError(message);
  }

  final rawData = response["data"];
  final deviceDetails = rawData is String ? jsonDecode(rawData) : rawData;

  if (deviceDetails is Map) {
    final senseId = deviceDetails["sense_id"];
    final requestId = deviceDetails["request_id"];
    print("Sense ID: $senseId");
    print("Request ID: $requestId");
  }
}

Add import 'dart:convert'; when decoding a JSON string response.

Security events

Subscribe to the security event stream to receive RASP and device security signals:

import 'dart:async';

late final StreamSubscription<Map<dynamic, dynamic>> securitySubscription;

@override
void initState() {
  super.initState();

  securitySubscription = Sense.securityEvents.listen((event) {
    final type = event["type"];
    final value = event["value"];
    print("Security event: $type -> $value");
  });
}

@override
void dispose() {
  securitySubscription.cancel();
  super.dispose();
}

Platform setup

Run the normal Flutter dependency and build commands after adding the package:

flutter pub get
flutter run

Ensure the Android and iOS project settings required by the signals you enable are configured in the host application.