dymatrix_flutter 1.0.0 copy "dymatrix_flutter: ^1.0.0" to clipboard
dymatrix_flutter: ^1.0.0 copied to clipboard

A Dymatrix analytics plugin for Flutter.

example/lib/main.dart

// Copyright © 2025 DYMATRIX GmbH

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dymatrix_flutter/dymatrix_flutter.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late final WebViewController controller;

  String? visitorId;
  String? sessionId;
  String? lastWebViewMessage;

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

    controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..addJavaScriptChannel(
            'DymatrixFlutter',
            onMessageReceived: (JavaScriptMessage message) async {
              setState(() {
                lastWebViewMessage = message.message;
              });
              if (kDebugMode) {
                debugPrint('onMessageReceived: ${message.message}');
              }
              final json = jsonDecode(message.message);
              final content = json['content'] as String?;
              final event = PageViewEvent();
              event.content = content;
              await Dymatrix.instance.addPageView(event);
            },
          );

    init();
  }

  Future<void> init() async {
    await Dymatrix.instance.init(clientKey: "xxxxx");
    await refreshUi();
  }

  Future<void> addTrackingEvents() async {
    final product = BasketItem(
      productId: 'prod-001',
      sku: 'sku-001',
      productName: 'Example Product',
      price: 123.45,
      productGroup: 'Electronics',
      quantity: 1,
      variants: ['Color: Red', 'Size: M', 'Material: Cotton'],
    );

    // Content
    final pageView1 = PageViewEvent(content: 'Test');
    await Dymatrix.instance.addPageView(pageView1);

    // Register
    final register = Register(userId: 'user-001', resultCode: 0);
    final pageView2 = PageViewEvent(content: 'Register', register: register);
    await Dymatrix.instance.addPageView(pageView2);

    // Login
    final login = Login(userId: 'user-001', resultCode: 0);
    final pageView3 = PageViewEvent(content: 'Login', login: login);
    await Dymatrix.instance.addPageView(pageView3);

    // Target
    final target = Target(
      target: 'target-001',
      additionalInfo: 'target details',
      score: 2,
      rule: TargetRule.all,
    );
    final pageView4 = PageViewEvent(content: 'Target', target: target);
    await Dymatrix.instance.addPageView(pageView4);

    // Search
    final search = Search(queryString: 'smartphone', numberOfHits: 2);
    final pageView5 = PageViewEvent(content: 'Search', search: search);
    await Dymatrix.instance.addPageView(pageView5);

    // Product viewed
    final pageView6 = PageViewEvent(content: 'Viewed');
    pageView6.addProductViewedEvent(product);
    await Dymatrix.instance.addPageView(pageView6);

    // Product added to basket
    final pageView7 = PageViewEvent(content: 'Added');
    pageView7.addProductAddedToBasketEvent(product);
    await Dymatrix.instance.addPageView(pageView7);

    // Product bought
    final pageView8 = PageViewEvent(content: 'Bought');
    pageView8.addProductBoughtEvent(product);
    await Dymatrix.instance.addPageView(pageView8);

    // Bill
    final bill = Bill(
      billId: 'bill-001',
      customerId: 'cust-001',
      total: 123.45,
      country: 'Germany',
      cip: '123456',
      city: 'Berlin',
    );
    final pageView9 = PageViewEvent(content: 'Bill', bill: bill);
    await Dymatrix.instance.addPageView(pageView9);
  }

  Future<void> refreshUi() async {
    final visitorId = await Dymatrix.instance.getVisitorId();
    final sessionId = await Dymatrix.instance.getSessionId();

    setState(() {
      this.visitorId = visitorId;
      this.sessionId = sessionId;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Builder(
        builder: (context) {
          return Scaffold(
            appBar: AppBar(title: const Text('Dymatrix example')),
            body: ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                ListTile(
                  title: Text('Visitor ID'),
                  subtitle: Text('$visitorId'),
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: visitorId ?? ''));
                  },
                ),
                ListTile(
                  title: Text('Session ID'),
                  subtitle: Text('$sessionId'),
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: sessionId ?? ''));
                  },
                ),
                ListTile(
                  title: Text('Last Message from WebView'),
                  subtitle: Text('$lastWebViewMessage'),
                  onTap: () {
                    Clipboard.setData(
                      ClipboardData(text: lastWebViewMessage ?? ''),
                    );
                  },
                ),
                SizedBox(height: 16),
                TextButton(
                  onPressed: () async {
                    final newSettings = await showDialog<PrivacySettings>(
                      context: context,
                      builder:
                          (context) => SimpleDialog(
                            title: Text('Select Privacy Settings'),
                            children:
                                PrivacySettings.values.map((option) {
                                  return SimpleDialogOption(
                                    onPressed: () {
                                      Navigator.pop(context, option);

                                      ScaffoldMessenger.of(
                                        context,
                                      ).showSnackBar(
                                        SnackBar(
                                          content: Text(
                                            'Selected privacy settings: ${option.label}',
                                          ),
                                        ),
                                      );
                                    },
                                    child: Text(option.label),
                                  );
                                }).toList(),
                          ),
                    );

                    await Dymatrix.instance.setPrivacySettings(newSettings);
                    await refreshUi();
                  },
                  child: Text('Change Privacy Settings'),
                ),
                TextButton(
                  onPressed: () async {
                    final newTimeout = await showDialog<int?>(
                      context: context,
                      builder:
                          (context) => SimpleDialog(
                            title: Text('Change Auto Transmit Timeout'),
                            children:
                                [null, 1, 10, 60, 300].map((option) {
                                  final title = switch (option) {
                                    null => 'No timeout',
                                    1 => '1 second',
                                    10 => '10 seconds',
                                    60 => '1 minute',
                                    300 => '5 minutes',
                                    _ => 'Unknown',
                                  };

                                  return SimpleDialogOption(
                                    onPressed: () {
                                      Navigator.pop(context, option);

                                      ScaffoldMessenger.of(
                                        context,
                                      ).showSnackBar(
                                        SnackBar(
                                          content: Text(
                                            'Selected timeout: $title',
                                          ),
                                        ),
                                      );
                                    },
                                    child: Text(title),
                                  );
                                }).toList(),
                          ),
                    );

                    await Dymatrix.instance.setBatchAutoTransmitTimeout(
                      newTimeout,
                    );
                  },
                  child: Text('Change Auto Transmit Timeout'),
                ),
                TextButton(
                  onPressed: () async {
                    await Dymatrix.instance.setPrivacySettings(null);
                  },
                  child: Text('Clear Privacy Settings'),
                ),
                TextButton(
                  onPressed: () async {
                    await Dymatrix.instance.startNextSession();
                  },
                  child: Text('Start New Session'),
                ),
                TextButton(
                  onPressed: () async {
                    addTrackingEvents();
                  },
                  child: Text('Add Tracking Events'),
                ),
                TextButton(
                  onPressed: () async {
                    await Dymatrix.instance.submitBatch();
                  },
                  child: Text('Send Tracking Events'),
                ),
                TextButton(
                  onPressed: () async {
                    controller.loadRequest(
                      Uri.parse(
                        'http://192.168.178.63:8080/example/ExampleWebsite.html',
                      ),
                    );

                    showModalBottomSheet<void>(
                      context: context,
                      showDragHandle: true,
                      builder: (BuildContext context) {
                        return WebViewWidget(controller: controller);
                      },
                    );
                  },
                  child: Text('Open WebView'),
                ),
                if (Platform.isIOS)
                  TextButton(
                    onPressed: () async {
                      final newLoggingEnabled = await showDialog<bool?>(
                        context: context,
                        builder:
                            (context) => SimpleDialog(
                              title: Text('Change logging enabled'),
                              children:
                                  [true, false].map((option) {
                                    final title = switch (option) {
                                      true => 'Enable logging',
                                      false => 'Disable logging',
                                    };

                                    return SimpleDialogOption(
                                      onPressed: () {
                                        Navigator.pop(context, option);

                                        ScaffoldMessenger.of(
                                          context,
                                        ).showSnackBar(
                                          SnackBar(
                                            content: Text(
                                              'Logging enabled: $option',
                                            ),
                                          ),
                                        );
                                      },
                                      child: Text(title),
                                    );
                                  }).toList(),
                            ),
                      );

                      await Dymatrix.instance.setLoggingEnabled(
                        newLoggingEnabled ?? false,
                      );
                    },
                    child: Text('Change logging enabled'),
                  ),
              ],
            ),
          );
        },
      ),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [Locale('en')],
    );
  }
}
1
likes
130
points
92
downloads

Documentation

API reference

Publisher

verified publisherdymatrix.de

Weekly Downloads

A Dymatrix analytics plugin for Flutter.

Homepage

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on dymatrix_flutter

Packages that implement dymatrix_flutter