tracker_flutter 2.3.1 copy "tracker_flutter: ^2.3.1" to clipboard
tracker_flutter: ^2.3.1 copied to clipboard

A flutter plugin for tracking events from Flutter. The given events will be sent to the native Tracker library.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:terra_flutter/terra_app.dart';
import 'package:tracker_flutter/event_body/event_body.dart';
import 'package:tracker_flutter/terra_tracker.dart';

const terraAppName = "tracker-flutter";

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

RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  bool isTerraInitialized = false;
  String? errorMessage;

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

  void _initTerraTracker() async {
    try {
      await TerraApp.initTerraApp(appName: terraAppName);
      final terraTracker = await TerraTracker.getInstance(terraAppName);
      terraTracker.setUserInfo(userId: "user-id", phoneNumber: "0912345678");
      setState(() {
        isTerraInitialized = true;
      });
    } on Exception catch (error) {
      setState(() {
        errorMessage = error.toString();
      });
    }
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    if (!isTerraInitialized) {
      return Container(
        color: Colors.white,
        child: Column(
          children: [if (errorMessage != null) Text(errorMessage ?? "")],
        ),
      );
    }

    return MaterialApp(
      title: 'Tracker Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
      navigatorObservers: [routeObserver],
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

abstract class BaseAppState<T extends StatefulWidget> extends State<T> {
  Future<TerraTracker> getTerraTracker() async {
    return TerraTracker.getInstance(terraAppName);
  }
}

class _MyHomePageState extends BaseAppState<MyHomePage> with RouteAware {
  void _trackAlert() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackAlertEvent(
      AlertEventBody(
        alertType: AlertType.popUp,
        alertMessage: "testAlertMessage",
        attr2: "testAttr2",
      ),
    );
  }

  void _trackCart() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackCartEvent(
      CartEventBody(
        eventName: CartEventName.addToCart,
        cartId: "testCartId",
        skuId: "210801335",
        skuName: "testSkuName",
        price: 100000,
        quantity: 10,
        status: Status.success,
        sdkId: "tracker_flutter_demo",
        sdkVersion: "0.0.1",
        attr3: "testAttr3",
      ),
    );
  }

  void _trackCheckout() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackCheckoutEvent(
      CheckoutEventBody(
        orderId: "orderId",
        amountBeforeDiscount: 100000.0,
        amountAfterDiscount: 90000.0,
        discountAmount: 10000.0,
        products: [
          Product(
              skuId: "skuId_1",
              skuName: "skuName_1",
              price: 25500.0,
              promotionPrice: 25500.0,
              quantity: 10),
          Product(
              skuId: "skuId_2",
              skuName: "skuName_2",
              price: 50000.0,
              promotionPrice: 50000.0,
              quantity: 2),
        ],
        paymentMethod: PaymentMethod.cash,
        status: Status.success,
        tax: 10.0,
        shippingFee: 25000.00,
        shippingAddressCode: "1000",
        note: "test note",
        attr3: "testAttr3",
      ),
    );
  }

  void _trackCustom() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackCustomEvent(
      CustomEventBody(
        category: "testCategory",
        action: "testAction",
        label: "testLabel",
        property: "testProperty",
        value: 99,
      ),
    );
  }

  void _trackError() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackErrorEvent(
      ErrorEventBody(
        apiCall: "https://error-api.abc",
        httpResponseCode: 200,
        errorSource: ErrorSource.http,
        errorCode: "40001",
        errorMessage: "testErrorMessage",
        apiPayload: "{\"sku\":\"123456\"}",
        responseJson: "{\"code\":\"403\",\"message\":\"No permission to access\"}",
        attr4: "testAttr4",
        attr5: "testAttr5",
      ),
    );
  }

  void _trackInteraction() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackInteractionEvent(
      InteractionContentEventBody(
        interaction: Interaction.click,
        regionName: "testRegionName",
        contentName: "testContentName",
        target: "testTarget",
        payload: "{\"example\":\"payload\"}",
        sdkId: "tracker-flutter",
        sdkVersion: "0.0.1",
      ),
    );
  }

  void _trackPayment() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackPaymentEvent(
      PaymentEventBody(
        orderId: "orderId",
        amount: 1000000,
        paymentMethod: PaymentMethod.cash,
        status: Status.failed,
        statusCode: 10000,
        attr5: "testAttr5",
      ),
    );
  }

  void _trackScan() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackScanEvent(
      ScanEventBody(
        scanId: "scanId",
        regionName: "testRegionName",
        target: "testTarget",
        attr1: "testAttr1",
      ),
    );
  }

  void _trackSearch() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackSearchEvent(
      SearchEventBody(
        params: SearchParams(
            channel: "channel", terminal: "terminal", keyword: "keyword", page: 3, limit: 10),
        keywords: ["a", "b"],
        order: ["price_ascending"],
        sort: ["price", "promotionPrice"],
      ),
    );
  }

  void _trackVisible() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackVisibleContentEvent(
      [
        VisibleContentEventBody(
          index: 0,
          contentName: "testContentName1",
          regionName: "testRegionName",
          sdkVersion: "0.0.1",
          payload: "1100"
        ),
        VisibleContentEventBody(
          index: 1,
          contentName: "testContentName2",
          regionName: "testRegionName",
          sdkVersion: "0.0.1",
          sdkId: "flutter-tracker",
            payload: "1100"
        )
      ],
    );
  }

  void _trackScreenViewForceTrack() async {
    final terraTracker = await getTerraTracker();

    terraTracker.trackScreenViewEvent(
      ScreenViewEventBody(
        eventName: ScreenEventName.enterScreenView, // enter or exit screen
        screenName: "home", // new screen just displayed to user
        contentType: "banner", // screen type, somewhat the group that this screen belongs to
        referrer: "refererScreen", // the screen before we enter this screen
        forceTrack: true,
      ),
    );
    final startTime = await terraTracker.getCurrentTime();
    await Future.delayed(const Duration(milliseconds: 2000));
    final endTime = await terraTracker.getCurrentTime();
    print("loadingTime: ${endTime - startTime}");

    terraTracker.trackCustomEvent(
      CustomEventBody(
        attr1: (endTime - startTime).toString(),
        attr2: "home",
        attr3: "page_load_time",
      ),
    );
  }

  void _trackPageLoadingTime() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackPageLoadingTime(
      screenName: 'Test Screen Name',
      pageLoadTimeInMillis: 1110,
      sdkId: "213",
      sdkVersion: "2321",
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void didPush() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackScreenViewEvent(
      ScreenViewEventBody(
        eventName: ScreenEventName.enterScreenView,
        screenName: "home",
        contentType: "banner",
        forceTrack: false,
      ),
    );
  }

  @override
  void didPop() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackScreenViewEvent(
      ScreenViewEventBody(
        eventName: ScreenEventName.exitScreenView,
        screenName: "home",
        contentType: "banner",
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    void _goToNextScreen() {
      Navigator.push(context, MaterialPageRoute(builder: (context) => const SecondPage()));
    }

    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            icon: const Icon(
              Icons.arrow_forward,
              color: Colors.white,
            ),
            onPressed: _goToNextScreen,
          )
        ],
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
                onPressed: _trackAlert,
                child: const Text(
                  'track alert',
                )),
            TextButton(
                onPressed: _trackCart,
                child: const Text(
                  'track cart',
                )),
            TextButton(
                onPressed: _trackCheckout,
                child: const Text(
                  'track checkout',
                )),
            TextButton(
                onPressed: _trackCustom,
                child: const Text(
                  'track custom',
                )),
            TextButton(
                onPressed: _trackError,
                child: const Text(
                  'track error',
                )),
            TextButton(
                onPressed: _trackInteraction,
                child: const Text(
                  'track interaction',
                )),
            TextButton(
                onPressed: _trackPayment,
                child: const Text(
                  'track payment',
                )),
            TextButton(
                onPressed: _trackScan,
                child: const Text(
                  'track scan',
                )),
            TextButton(
                onPressed: _trackSearch,
                child: const Text(
                  'track search',
                )),
            TextButton(
                onPressed: _trackVisible,
                child: const Text(
                  'track visible',
                )),
            TextButton(
                onPressed: _trackScreenViewForceTrack,
                child: const Text(
                  'track screen view - force track',
                )),
            TextButton(
                onPressed: _trackPageLoadingTime,
                child: const Text(
                  'track page loading time',
                )),
          ],
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  State<SecondPage> createState() => _SecondPageState();
}

class _SecondPageState extends BaseAppState<SecondPage> with RouteAware {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void didPush() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackScreenViewEvent(
      ScreenViewEventBody(
        eventName: ScreenEventName.enterScreenView,
        screenName: "second",
        contentType: "banner",
      ),
    );
  }

  @override
  void didPop() async {
    final terraTracker = await getTerraTracker();
    terraTracker.trackScreenViewEvent(
      ScreenViewEventBody(
        eventName: ScreenEventName.exitScreenView,
        screenName: "second",
        contentType: "banner",
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    void _goBack() {
      Navigator.pop(context);
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Page"),
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: _goBack,
        ),
      ),
      body: Center(
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            Text('This is the second screen'),
          ],
        ),
      ),
    );
  }
}
0
likes
130
points
375
downloads

Publisher

unverified uploader

Weekly Downloads

A flutter plugin for tracking events from Flutter. The given events will be sent to the native Tracker library.

Homepage

Documentation

API reference

License

unknown (license)

Dependencies

flutter

More

Packages that depend on tracker_flutter