tambi_flutter_sdk 0.0.4 copy "tambi_flutter_sdk: ^0.0.4" to clipboard
tambi_flutter_sdk: ^0.0.4 copied to clipboard

Effortless cx automation for startups

example/lib/main.dart

import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:tambi_flutter_sdk/tambi_flutter_sdk.dart';
import 'package:tambi_flutter_sdk_example/home_page.dart';
import 'package:tambi_flutter_sdk_example/tambi_service.dart';
import 'firebase_options.dart'; // Generated by the FlutterFire CLI

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
// Define a top-level named handler for background/terminated messages.
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Background message received");
  log("Handling a background message: ${message.messageId}");
  if (Tambi.isTambiNotification(message.data)) {
    // Tambi.handlePushNotification(message.notification!.toMap());
    return;
  }
}

// Initialize local notifications
void initializeLocalNotifications() {
  var initializationSettingsAndroid = const AndroidInitializationSettings('@mipmap/ic_launcher');
  var initializationSettingsIOS = const DarwinInitializationSettings(
    requestSoundPermission: true,
    requestBadgePermission: false,
    requestAlertPermission: false,
    defaultPresentAlert: true,
  );
  var initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
  flutterLocalNotificationsPlugin.initialize(initializationSettings);
}

// Request notification permission for iOS devices.
void requestNotificationPermission() async {
  NotificationSettings settings = await FirebaseMessaging.instance.requestPermission(
    alert: true,
    badge: true,
    sound: true,
    provisional: false,
  );
}

void init({Widget? widget}) {
  requestNotificationPermission();
  initializeLocalNotifications();

  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    log("Handling a foreground message: ${message.toMap()}");
    // Show notification for foreground message
    var androidPlatformChannelSpecifics = const AndroidNotificationDetails('your_channel_id', 'your_channel_name',
        channelDescription: 'your_channel_description', importance: Importance.max, priority: Priority.high, ticker: 'ticker');
    var iOSPlatformChannelSpecifics = const DarwinNotificationDetails(
      presentAlert:
          true, // Present an alert when the notification is displayed and the application is in the foreground (only from iOS 10 onwards)
      presentBadge:
          true, // Present the badge number when the notification is displayed and the application is in the foreground (only from iOS 10 onwards)
      presentSound: true,
    );
    var platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);
    if (Tambi.isTambiNotification(message.data)) {
      ///ensure Tambi is initialized and user is also set up before this
      setUpTambiUser(openDialogValue: true);
      Tambi.handlePushNotification(message.notification!.toMap(), navigatorKey.currentState!.context);
    } else {
      flutterLocalNotificationsPlugin.show(
          0, // Notification ID
          message.notification?.title ?? 'New Message', // Notification Title
          message.notification?.body ?? 'You have a new message.', // Notification Body
          platformChannelSpecifics,
          payload: 'New payload');
    }
  });

  FirebaseMessaging.instance.getInitialMessage().then((message) async {
    if (message != null) {
      log("Message from initial");
      if (Tambi.isTambiNotification(message.data) && Platform.isIOS) {
        setUpTambiUser(openDialogValue: true);
        TambiSDK.openFromNotification(
            context: navigatorKey.currentState!.context, isChatOpened: !TambiSDK.shouldShowNotificationInForeground());
      }
    }
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
    if (Tambi.isTambiNotification(message.data)) {
      log("Message from TambiSDK");
      setUpTambiUser(openDialogValue: true);
      TambiSDK.openFromNotification(
          context: navigatorKey.currentState!.context, isChatOpened: !TambiSDK.shouldShowNotificationInForeground());
    }
  });
  runApp(
    widget ?? const MyApp(),
  );
}

void setUpTambiUser({bool? openDialogValue}) async {
  String? value = await storage.read(key: userData);
  TambichatUser? user;
  if (value != null) {
    user = TambichatUser.fromJson(jsonDecode(value));
    String? key = await storage.read(key: appKey);
    String? keyValue = await storage.read(key: appValue);
    TambiSDK.setUpLoggedInUser(user, key!, keyValue!);
  }
  if(openDialogValue!=null) {
    openDialog.value = openDialogValue;
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  init();
}

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

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

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    return MaterialApp(
      title: 'Tambi Flutter SDK Example',
      debugShowCheckedModeBanner: false,
      navigatorKey: navigatorKey,
      theme: ThemeData(
        primaryColor: Color(0xFF6FE100),
      ),
      home: Scaffold(
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Color(0xFFFFFCFB),
          bottomOpacity: 0,
          scrolledUnderElevation: 0,
          surfaceTintColor: Color(0xFFFFFCFB),
          centerTitle: true,
          title: const Column(
            children: [
              Text(
                "Tambi SDK Example",
                style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500),
              ),
            ],
          ),
        ),
        backgroundColor: Color(0xFFFFFCFB),
        body: const HomePage(),
      ),
    );
  }
}