0

I am not able to navigate in background and terminate state of app to my notification screen i tried many things but it shows Bottomnavigation only when my app is in terminated or in background state

import 'dart:io';

import 'dart:math';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:http/http.dart' as http;

import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shimushi/notification/view/notification_screen.dart';

import '../database/database_helper.dart';
import '../notification/view/view_model/notification_refresh_data.dart';

class NotificationServices {
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  FirebaseMessaging messaging = FirebaseMessaging.instance;
  final NotificationDatabaseHelper _databaseHelper =
      NotificationDatabaseHelper();

  String? token;

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  void initLocalNotification(
      BuildContext context, RemoteMessage message) async {
    var androidInitializationSettings =
        const AndroidInitializationSettings('@mipmap/ic_launcher');
    var iosInitializationSettings = const DarwinInitializationSettings();

    var initializationSettings = InitializationSettings(
        android: androidInitializationSettings, iOS: iosInitializationSettings);
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse: (details) {
        print('Manoj');
        Navigator.pushNamed(context, '/notification');
      },
      // onDidReceiveBackgroundNotificationResponse: (details) {
      //   print('Background');
      //   print(navigatorKey.currentContext);
      //   navigatorKey.currentState!.pushNamed('/notification');
      // },
    );
  }

  void requestNotificationPermission() async {
    NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        announcement: true,
        carPlay: true,
        criticalAlert: true,
        provisional: true,
        sound: true,
        badge: true);
    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus ==
        AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User denied permission');
    }
  }

  Future<String> getDeviceToken() async {
    token = await messaging.getToken();
    updateUserToken();

    return token!;
  }

  void isTokenRefresh() {
    messaging.onTokenRefresh.listen((event) {
      event.toString();
      print('refresh');
    });
  }

  Future<void> updateUserToken() async {
    final pref = await SharedPreferences.getInstance();
    final url =
        Uri.parse('http://demoapp.citronsoftwares.com/api/User/UpdateToken');
    final body = {
      'mobno': pref.getString('mobno').toString(),
      'fcmtoken': token,
      'imei': '',
    };
    try {
      final response = await http.post(url, body: body);

      if (response.statusCode == 200) {
        // Request successful
        print(response.body);
        print('Token updated successfully');
      } else {
        // Request failed
        print('Failed to update token. Status code: ${response.statusCode}');
      }
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> showNotification(
      RemoteMessage message, BuildContext context) async {
    AndroidNotificationChannel androidNotificationChannel =
        AndroidNotificationChannel(Random.secure().nextInt(100000).toString(),
            'High Importance Notification',
            importance: Importance.max);
    AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      androidNotificationChannel.id.toString(),
      androidNotificationChannel.name.toString(),
      channelDescription: 'Your channel description',
      importance: Importance.high,
      priority: Priority.high,
      ticker: 'ticker',
      playSound: true,
    );

    const DarwinNotificationDetails darwinNotificationDetails =
        DarwinNotificationDetails(
            presentAlert: true, presentBadge: true, presentSound: true);

    NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails, iOS: darwinNotificationDetails);

    Future.delayed(Duration.zero, () {
      flutterLocalNotificationsPlugin.show(
          0,
          message.data['msgtype'] ?? '', // Use msgtype as the title
          message.data['content'] ?? '',
          notificationDetails,
          payload: 'Notification');
      Provider.of<NotificationRefreshProvider>(context, listen: false)
          .refresh();
    });
    // handleMessage(context, message);
  }

  void firebaseInit(BuildContext context) {
    FirebaseMessaging.onMessage.listen((message) {
      print("message data is :${message.data.toString()}");
      if (Platform.isAndroid) {
        initLocalNotification(context, message);
        showNotification(message, context);
      } else {
        showNotification(message, context);
      }

      NotificationData notification = NotificationData(
        id: DateTime.now()
            .millisecondsSinceEpoch, // You can generate a unique ID based on your requirements
        title: message.data['msgtype'] ?? '',
        content: message.data['content'] ?? '',
      );
      _databaseHelper.insertNotification(notification);
    });
  }

// set the onSelectNotification callback function

  void showNotificationInBackground(RemoteMessage message) {
    AndroidNotificationChannel androidNotificationChannel =
        AndroidNotificationChannel(Random.secure().nextInt(100000).toString(),
            'High Importance Notification',
            importance: Importance.max);
    AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      androidNotificationChannel.id.toString(),
      androidNotificationChannel.name.toString(),
      channelDescription: 'Your channel description',
      importance: Importance.high,
      priority: Priority.high,
      ticker: 'ticker',
      playSound: true,
    );

    const DarwinNotificationDetails darwinNotificationDetails =
        DarwinNotificationDetails(
            presentAlert: true, presentBadge: true, presentSound: true);

    NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails, iOS: darwinNotificationDetails);

    flutterLocalNotificationsPlugin.show(0, message.data['msgtype'] ?? '',
        message.data['content'] ?? '', notificationDetails,
        payload: 'Notification');
  }
}
MendelG
  • 14,885
  • 4
  • 25
  • 52

0 Answers0