import 'dart:convert'; import 'dart:io'; import 'package:chatnew/screens/chatList.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; const AndroidNotificationChannel channel = AndroidNotificationChannel( 'high_importance_channel', // id 'High Importance Notifications', // title description: 'This channel is used for important notifications.', // description importance: Importance.high, playSound: true); final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); final GlobalKey navigatorKey = GlobalKey(); late final StreamChatClient client; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); // Get device token var deviceToken; FirebaseMessaging.instance.getToken().then((value) { deviceToken = value; print("Androidfbstoken:{$deviceToken}"); // toast(BuildContext , token); }); // Set up Firebase messaging handlers FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); FirebaseMessaging messaging = FirebaseMessaging.instance; NotificationSettings settings = await messaging.requestPermission( alert: true, announcement: false, badge: true, carPlay: false, criticalAlert: false, provisional: false, sound: true, ); print('User granted permission: ${settings.authorizationStatus}'); await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( alert: true, badge: true, sound: true, ); await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation()?.createNotificationChannel(channel); const InitializationSettings initializationSettings = InitializationSettings( android: AndroidInitializationSettings('@mipmap/ic_launcher'), iOS: DarwinInitializationSettings()); flutterLocalNotificationsPlugin.initialize( initializationSettings, onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) async { if (notificationResponse.payload != null) { print("Foreground notification tapped: ${notificationResponse.payload}"); // Parse payload JSON string back to Map try { var payloadData = json.decode(notificationResponse.payload!); String type = payloadData['type']; print('Notification type: $type'); } catch (e) { print("Error parsing notification payload: $e"); } } }, ); FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = message.notification?.android; if (notification != null && android != null) { print('A new message received: ${notification.title}'); print('RemoteMessage data: ${message.data.toString()}'); showNotification(notification, android, message.data); } else { print('Null A new message received'); } }); FirebaseMessaging.onMessageOpenedApp.listen((message) { _handleMessage(message); print("onMessageOpenedApp:${message.data['type']}"); }); client = StreamChatClient( 'b4fqt99hw43q', logLevel: Level.ALL ); await client.connectUser( User(id: '1324635'), 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoibnV0c2J5In0.ECApkmJgBMAhcn90mqX67SAblSUE_CYhUuaWKey84jc', ); runApp(const MyApp()); } Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async { await Firebase.initializeApp(); print("Background message received: ${message.data}"); // Handle background message if (message.data.isNotEmpty) { try { var parsedData = jsonDecode(message.data['rendered_message']); print("Parsed Message Data: $parsedData"); } catch (e) { print("Error parsing background notification payload: $e"); } } } void showNotification(RemoteNotification notification, AndroidNotification android, Map data) async { AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( channel.id, // Ensure this matches channel.name, // Ensure this matches importance: Importance.max, priority: Priority.high, playSound: true, ); NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics); await flutterLocalNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, platformChannelSpecifics, payload: jsonEncode(data), // Ensure the data is correctly encoded ); } void _handleMessage(RemoteMessage message) { print("Notification tapped with payload: ${message.notification?.title}"); print("Message Data: ${message.data}"); if (message.data.isNotEmpty) { try { var parsedData = jsonDecode(message.data['rendered_message']); print("Parsed Message Data: $parsedData"); // Handle the notification, e.g., navigate to a specific screen } catch (e) { print("Error parsing notification payload: $e"); } } } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge, overlays: []); return MaterialApp( builder: (BuildContext context, Widget? child) { final MediaQueryData data = MediaQuery.of(context); return MediaQuery( data: data.copyWith(textScaleFactor: 1.0), child: child ?? Container(), ); }, themeMode: ThemeMode.light, theme: ThemeData( visualDensity: VisualDensity.adaptivePlatformDensity, splashColor: Colors.transparent, highlightColor: Colors.transparent, hoverColor: Colors.transparent, scaffoldBackgroundColor: Colors.white, dialogBackgroundColor: Colors.white, cardColor: Colors.white, searchBarTheme: const SearchBarThemeData(), tabBarTheme: const TabBarTheme(), dialogTheme: const DialogTheme( shadowColor: Colors.white, surfaceTintColor: Colors.white, backgroundColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(5.0)), ), ), buttonTheme: const ButtonThemeData(), popupMenuTheme: const PopupMenuThemeData( color: Colors.white, shadowColor: Colors.white), appBarTheme: const AppBarTheme( surfaceTintColor: Colors.white, ), cardTheme: const CardTheme( shadowColor: Colors.white, surfaceTintColor: Colors.white, color: Colors.white, ), textSelectionTheme: TextSelectionThemeData( selectionHandleColor: Colors.transparent, ), textButtonTheme: TextButtonThemeData( style: ButtonStyle(), ), bottomSheetTheme: const BottomSheetThemeData( surfaceTintColor: Colors.white, backgroundColor: Colors.white), colorScheme: const ColorScheme.light(background: Colors.white) .copyWith(background: Colors.white), ), title: 'Nutsby', debugShowCheckedModeBanner: false, navigatorKey: navigatorKey, home: chatList(client: client), ); } }