Skip to main content

jatayu_flutter 0.4.1 copy "jatayu_flutter: ^0.4.1" to clipboard
jatayu_flutter: ^0.4.1 copied to clipboard

unlisted

Mobile analytics, attribution, observability, and remote configuration for the Jatayu platform.

example/lib/main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:jatayu_flutter/jatayu_flutter.dart';

import 'services/onesignal_service.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize OneSignal before runApp. Do NOT request push permission here —
  // the push-subscription verification dialog requests it on tap.
  await OneSignalService().initialize();

  runApp(const ExampleApp());
}

class ExampleApp extends StatelessWidget {
  const ExampleApp({super.key});
  @override
  Widget build(BuildContext context) => MaterialApp(
    title: 'Jatayu SDK',
    theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xff9b83f4), brightness: Brightness.dark), useMaterial3: true),
    home: const ExampleScreen(),
  );
}

class ExampleScreen extends StatefulWidget {
  const ExampleScreen({super.key});
  @override
  State<ExampleScreen> createState() => _ExampleScreenState();
}

class _ExampleScreenState extends State<ExampleScreen> {
  final endpoint = TextEditingController(text: const String.fromEnvironment('JATAYU_ENDPOINT', defaultValue: 'http://localhost:5173'));
  final keyInput = TextEditingController(text: const String.fromEnvironment('JATAYU_PUBLIC_KEY'));
  final user = TextEditingController(text: 'example-user');
  JatayuClient? client;
  bool consent = false, busy = false;
  String status = 'Not connected';

  // Retained for the lifetime of this screen. OneSignal holds push observers
  // weakly on some platforms; a local-only closure would be deallocated and
  // the verification dialog would never appear.
  PushSubscriptionCallback? _pushSubscriptionCallback;
  bool _onesignalDialogShown = false;
  String? _oneSignalSubscriptionId;
  String? _lastForwardedPushId;

  @override
  void initState() {
    super.initState();
    _pushSubscriptionCallback = _onPushSubscriptionId;
    OneSignalService().addPushSubscriptionObserver(_pushSubscriptionCallback!);
  }

  void _onPushSubscriptionId(String? subscriptionId) {
    if (!mounted) return;
    setState(() => _oneSignalSubscriptionId = subscriptionId);
    // Forward the server-assigned subscription ID to Jatayu so the backend
    // can target this installation through OneSignal.
    if (isRegisteredPushSubscription(subscriptionId) &&
        client != null &&
        consent &&
        subscriptionId != _lastForwardedPushId) {
      _lastForwardedPushId = subscriptionId;
      final id = subscriptionId!;
      unawaited(client!
          .registerPushToken(token: id, provider: PushProvider.onesignal)
          .then((_) {
        if (mounted) {
          setState(
              () => status = 'Push registered with Jatayu via OneSignal');
        }
      }).catchError((Object error) {
        _lastForwardedPushId = null;
        if (mounted) {
          setState(() => status = 'Push forward failed: $error');
        }
      }));
    }
    // Show the verification dialog exactly once, on a real server-assigned ID.
    if (isRegisteredPushSubscription(subscriptionId) &&
        !_onesignalDialogShown) {
      _onesignalDialogShown = true;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        _showIntegrationCompleteDialog();
      });
    }
  }

  void _showIntegrationCompleteDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('Your OneSignal SDK integration is complete!'),
        content: const Text(
            'You can now send Push Notifications & In-App Messages through OneSignal. Tap below to enable push notifications.'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // The ONLY place push permission is requested.
              unawaited(OneSignalService().requestPermission());
            },
            child: const Text('Got it'),
          ),
        ],
      ),
    );
  }

  Future<void> _forwardExistingPushSubscription() async {
    final id = OneSignalService().pushSubscriptionId;
    if (isRegisteredPushSubscription(id) &&
        client != null &&
        consent &&
        id != _lastForwardedPushId) {
      _lastForwardedPushId = id;
      await client!
          .registerPushToken(token: id!, provider: PushProvider.onesignal);
    }
  }

  Future<void> perform(Future<void> Function() operation) async {
    setState(() => busy = true);
    try { await operation(); if (mounted) setState(() => status = 'Done · ${client?.pendingEventCount ?? 0} queued events'); }
    catch (error) { if (mounted) setState(() => status = error.toString()); }
    finally { if (mounted) setState(() => busy = false); }
  }

  @override
  void dispose() {
    if (_pushSubscriptionCallback != null) {
      OneSignalService()
          .removePushSubscriptionObserver(_pushSubscriptionCallback!);
      _pushSubscriptionCallback = null;
    }
    endpoint.dispose(); keyInput.dispose(); user.dispose();
    unawaited(client?.dispose() ?? Future.value()); super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(appBar: AppBar(title: const Text('Jatayu SDK')), body: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 520), child: ListView(padding: const EdgeInsets.all(24), children: [
    TextField(controller: endpoint, decoration: const InputDecoration(labelText: 'Jatayu endpoint')),
    const SizedBox(height: 12),
    TextField(controller: keyInput, decoration: const InputDecoration(labelText: 'Public SDK key')),
    SwitchListTile(contentPadding: EdgeInsets.zero, title: const Text('Analytics consent'), value: consent, onChanged: busy ? null : (value) { setState(() => consent = value); if (client != null) unawaited(perform(() => client!.setConsent(value))); }),
    FilledButton(onPressed: busy || client != null ? null : () => perform(() async {
      client = await JatayuClient.create(JatayuOptions(endpoint: endpoint.text.trim(), writeKey: keyInput.text.trim(), consent: consent, allowInsecureLocalhost: true));
      await _forwardExistingPushSubscription();
    }), child: const Text('Connect')),
    const SizedBox(height: 24), Text(status),
    if (client?.installationId != null) SelectableText('Installation: ${client!.installationId}'),
    if (_oneSignalSubscriptionId != null &&
        isRegisteredPushSubscription(_oneSignalSubscriptionId))
      SelectableText('OneSignal: ${_oneSignalSubscriptionId!}'),
    const SizedBox(height: 20),
    TextField(controller: user, decoration: const InputDecoration(labelText: 'User ID')),
    OutlinedButton(onPressed: busy || client == null || !consent ? null : () => perform(() async {
      await client!.identify(user.text, properties: {'name': 'Example user'}, setOnce: {'signup_source': 'example'});
      OneSignalService().login(user.text.trim());
    }), child: const Text('Identify user')),
    OutlinedButton(onPressed: busy || client == null || !consent ? null : () => perform(() => client!.setGroup('organization', 'demo', properties: {'plan': 'pro'})), child: const Text('Join demo group')),
    OutlinedButton(onPressed: busy || client == null || !consent ? null : () => perform(() async { await client!.track('product_view', {'product_id': 'premium'}); await client!.flush(); }), child: const Text('Send product_view')),
    OutlinedButton(onPressed: busy || client == null || !consent ? null : () {
      final messenger = ScaffoldMessenger.of(context);
      unawaited(perform(() async {
        await client!.fetchConfig();
        if (!mounted) return;
        messenger.showSnackBar(SnackBar(content: Text(client!.getString('welcome_message', fallback: 'No welcome_message configured'))));
      }));
    }, child: const Text('Fetch remote config')),
    OutlinedButton(onPressed: busy || client == null || !consent ? null : () => perform(() async { await client!.resetIdentity(); OneSignalService().logout(); _lastForwardedPushId = null; }), child: const Text('Reset identity')),
  ]))));
}
1
likes
0
points
56
downloads

Publisher

verified publisheraravindchowdary.com

Weekly Downloads

Mobile analytics, attribution, observability, and remote configuration for the Jatayu platform.

Repository (GitHub)
View/report issues

Topics

#analytics #attribution #remote-config

License

unknown (license)

Dependencies

crypto, flutter, http, shared_preferences, uuid

More

Packages that depend on jatayu_flutter

Packages that implement jatayu_flutter