antsomisdk 0.0.37 copy "antsomisdk: ^0.0.37" to clipboard
antsomisdk: ^0.0.37 copied to clipboard

This a an Antsomi Mobile SDK for Flutter.

example/lib/main.dart

import 'dart:convert';

import 'package:antsomisdk/cdp_event.dart';
import 'package:antsomisdk/inbox_items.dart';
import 'package:antsomisdk/media_json.dart';
import 'package:antsomisdk/screen_observer.dart';
import 'package:antsomi_example/detail_screen.dart';
import 'package:antsomi_example/navigator_key.dart';
import 'package:antsomi_example/notification_screen.dart';
import 'package:antsomi_example/sdk.dart';
import 'package:antsomi_example/webview_screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';

import 'package:uni_links/uni_links.dart';

bool _initialURILinkHandled = false;

void printError(dynamic err, [dynamic trace, dynamic message]) {}

void main() async {
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();

    AntsomiSDK.instance.config(
        appGroupId: "group.flutter.example.pro",
        portalId: '564890637',
        propsId: '564993464',
        applicationId: 'fbdfb60d-7ff6-41cd-8203-3ce029c51764');

    AntsomiSDK.instance.setCustomerProperties(customerId: "1998");
    AntsomiSDK.instance.resetUid();
    AntsomiSDK.instance
        .appInboxInit(destinationId: '8317604', audienceType: 'visitor');
    AntsomiSDK.instance.requestNotificationPermission();
    runApp(const MyApp());

    final event = CDPEvent(en: 'view_screenview');
    event.eventProps = {'screen_name': 'khanhhv'};
    AntsomiSDK.instance.track(event: event);

    AntsomiSDK.instance.setHandleChangeRouteTemplate(callback: (String route) {
      print("route: $route");
    });
  }, printError);
}

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

class _MyAppState extends State<MyApp> {
  late CDPEvent myCDPEvent;

  int _selectedIndex = 0;
  int _badgeCount = 0;
  List<String> _name = ['Home', 'Search', 'Notification', 'WebView'];
  late final List<Widget> _body;

  Future<void> getBadge() async {
    final count = await AntsomiSDK.instance.getUnreadMessageCount();
    print(count);
    AntsomiSDK.instance.resetCustomer();
    print("resetCustomer success");
    debugPrint("[UID]: ${await AntsomiSDK.instance.getUid()}");
    setState(() {
      _badgeCount = count ?? 0;
    });

    // MediaJson mediaJson = await AntsomiSDK.instance.getMediaJson(event: event);
    // print("webContents");
    // print(jsonEncode(mediaJson));
  }

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

    WidgetsFlutterBinding.ensureInitialized();

    getBadge();

    _body = [
      const Center(
        child: Icon(
          Icons.home,
          size: 150,
        ),
      ),
      const Center(
        child: Icon(
          Icons.search,
          size: 150,
        ),
      ),
      NotificationSreen(
        onReadMessage: (value) {
          setState(() {
            _badgeCount >= 0 ? _badgeCount = _badgeCount - value : 0;
          });
        },
        onReceiveNewMessage: () {
          setState(() {
            _badgeCount = _badgeCount + 1;
          });
        },
        onTapMessage: (p0) {
          NavigatorKey.instance.currentState
              ?.pushNamed("/detail", arguments: p0);
        },
      ),
      // const WebViewApp(
      //   url:
      //       "https://sandbox-template.ants.vn/thanghn1/test-notification.html?v=3",
      // )
    ];

    _initURIHandler();
    _incomingLinkHandler();
  }

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

  void onPressNavBar(int index) {
    setState(() {
      _selectedIndex = index;
    });
    AntsomiSDK.instance.trackScreen(name: _name[_selectedIndex]);
  }

  /// DEEP LINK HANDLER
  StreamSubscription? _streamSubscription;
  Future<void> _initURIHandler() async {
    if (!_initialURILinkHandled) {
      _initialURILinkHandled = true;

      try {
        final initialURI = await getInitialUri();
        if (initialURI != null) {
          debugPrint("Initial URI received $initialURI");
          if (!mounted) {
            return;
          }
          AntsomiSDK.instance.handleDeepLink(url: initialURI);
          final res = await AntsomiSDK.instance
              .getMessageById(messageId: initialURI.path.split('/')[1]);

          //Parse deep link if app open from another app(or web) when being terminated

          WidgetsBinding.instance.addPostFrameCallback((_) {
            NavigatorKey.instance.currentState
                ?.pushNamed("/detail", arguments: res);
          });
        } else {
          debugPrint("Null Initial URI received");
        }
      } on PlatformException {
        debugPrint("Failed to receive initial uri");
      } on FormatException {
        if (!mounted) {
          return;
        }
        debugPrint('Malformed Initial URI received');
      }
    }
  }

  void _incomingLinkHandler() async {
    if (!kIsWeb) {
      _streamSubscription = uriLinkStream.listen((Uri? uri) async {
        // Parse deep link and get information into CDP event
        AntsomiSDK.instance.handleDeepLink(url: uri!);
        final res = await AntsomiSDK.instance
            .getMessageById(messageId: uri.path.split('/')[1]);
        WidgetsBinding.instance.addPostFrameCallback((_) {
          NavigatorKey.instance.currentState
              ?.pushNamed("/detail", arguments: res);
        });
      }, onError: (Object err) {
        if (!mounted) {
          return;
        }
        debugPrint('Error occurred: $err');
      });
      if (!mounted) {
        return;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: NavigatorKey.instance,
      navigatorObservers: [ScreenObserver()],
      initialRoute: '/home',
      routes: {
        '/home': (context) => _homeWidget(),
      },
      onGenerateRoute: (settings) {
        switch (settings.name) {
          case '/detail':
            final arguments = settings.arguments;

            if (arguments is Map<String, String>) {
              final resultShow = arguments;
              return MaterialPageRoute(
                settings: settings,
                builder: (context) => DetailScreen(
                  heading: resultShow['heading']!,
                  content: resultShow['content']!,
                  urlImage: resultShow['imageURL']!,
                  time: resultShow['ctime']!,
                  name: resultShow['name']!,
                  onDispose: () {},
                ),
              );
            } else if (arguments is InboxItem) {
              final result = arguments;
              return MaterialPageRoute(
                settings: settings,
                builder: (context) => DetailScreen(
                  heading: result.heading!,
                  content: result.content!,
                  urlImage: result.imageUrl!,
                  time: result.dateCreated!.toIso8601String(),
                  name: result.appUrl!,
                  onDispose: () {},
                ),
              );
            }
        }
        return null;
      },
    );
  }

  Scaffold _homeWidget() {
    return Scaffold(
      body: IndexedStack(
        index: _selectedIndex,
        children: _body,
      ),
      bottomNavigationBar: BottomNavigationBar(
        unselectedItemColor: Colors.black,
        elevation: 0,
        selectedIconTheme: const IconThemeData(color: Colors.blue, size: 28),
        showUnselectedLabels: true,
        selectedLabelStyle: const TextStyle(color: Colors.blue),
        selectedItemColor: Colors.blue,
        onTap: onPressNavBar,
        currentIndex: _selectedIndex,
        items: <BottomNavigationBarItem>[
          const BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.home),
            label: "Home",
          ),
          const BottomNavigationBarItem(
              icon: Icon(CupertinoIcons.search), label: "Search"),
          BottomNavigationBarItem(
              icon: Stack(
                children: [
                  const Icon(CupertinoIcons.bell),
                  Positioned(
                    right: 0,
                    child: _badgeCount != 0
                        ? Container(
                            padding: const EdgeInsets.all(1),
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(10),
                            ),
                            constraints: const BoxConstraints(
                              minWidth: 16,
                              minHeight: 16,
                            ),
                            child: Text(
                              '$_badgeCount',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 10,
                              ),
                              textAlign: TextAlign.center,
                            ),
                          )
                        : Container(),
                  )
                ],
              ),
              label: "Notifications"),
          const BottomNavigationBarItem(
              icon: Icon(CupertinoIcons.cart), label: "Cart")
        ],
      ),
    );
  }
}
1
likes
130
points
125
downloads

Publisher

unverified uploader

Weekly Downloads

This a an Antsomi Mobile SDK for Flutter.

Homepage

Documentation

API reference

License

BSD-2-Clause (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on antsomisdk