antsomisdk 0.0.18 antsomisdk: ^0.0.18 copied to clipboard
This a an Antsomi Mobile SDK for Flutter.
import 'package:antsomisdk/cdp_event.dart';
import 'package:antsomisdk/inbox_items.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: "561236459",
propsId: "564994794",
applicationId: "406a9e34-09b5-42ee-89a9-8aeb7df78609");
AntsomiSDK.instance.setCustomerProperties(customerId: "1998");
AntsomiSDK.instance
.appInboxInit(destinationId: "8269964", audienceType: "customer");
runApp(const MyApp());
}, 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);
debugPrint("[UID]: ${await AntsomiSDK.instance.getUID()}");
setState(() {
_badgeCount = count ?? 0;
});
}
@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.parseDeepLink(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.parseDeepLink(uri!);
final res = await AntsomiSDK.instance
.getMessageById(messageId: uri.path.split('/')[1]);
WidgetsBinding.instance.addPostFrameCallback((_) {
NavigatorKey.instance.currentState
?.pushNamed("/detail", arguments: res);
AntsomiSDK.instance.track(event: myCDPEvent);
});
}, 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")
],
),
);
}
}