1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] FCM message not shown when app is closed in release mode

Discussão em 'Mobile' iniciado por Stack, Novembro 4, 2024 às 03:22.

  1. Stack

    Stack Membro Participativo

    I have used FCM along with Flutter local notification for receiving messages. Flutter local notifiation is used to show notification when app is in foreground.

    When I terminate the application and send a message from Firebase Console, the below message appears in the logcat.


    [ERROR:flutter/lib/ui/dart_runtime_hooks.cc(38)] Dart Error: Dart_LookupLibrary: library 'package:x/x/x/data/firebase_api.dart' not found.

    E/flutter ( 9510): [ERROR:flutter/shell/common/shell.cc(117)] Dart Error: Dart_LookupLibrary: library 'package:x/x/x/data/firebase_api.dart' not found.

    E/flutter ( 9510): [ERROR:flutter/shell/common/shell.cc(117)] Dart Error: Dart_LookupLibrary: library 'package:x/x/x/data/firebase_api.dart' not found.

    This is my class:

    class FirebaseAPI {

    final _firebaseMessaging = FirebaseMessaging.instance;

    final _localNotification = FlutterLocalNotificationsPlugin();



    // Notification channel (Android only)

    final AndroidNotificationChannel _androidNotificationChannel = const AndroidNotificationChannel(

    'high_importance_channel',

    'High Importance Notifications',

    description: 'This channel is used for important notifications.',

    importance: Importance.high,

    );



    FirebaseAPI() {

    // Initialize Firebase Messaging and Local Notification

    initNotification();

    }



    // Background message handler (needs to be a top-level function)

    static Future<void> handleBackgroundMessage(RemoteMessage message) async {

    print('Background Message Received: payload ${message.data}');



    // Extract title and body from the data payload

    String title = message.data['title_en'] ?? 'Default Title';

    String body = message.data['body_en'] ?? 'Default Body';



    final localNotifications = FlutterLocalNotificationsPlugin();

    await localNotifications.show(

    message.notification?.hashCode ?? 0,

    title,

    body,

    NotificationDetails(

    android: AndroidNotificationDetails(

    'high_importance_channel',

    'High Importance Notifications',

    channelDescription: 'This channel is used for important notifications.',

    importance: Importance.high,

    priority: Priority.high,

    icon: '@mipmap/aa', // Ensure this icon exists in your resources

    ),

    ),

    payload: jsonEncode(message.data),

    );

    }

    // Listen to messages when the app is closed





    // Foreground message handler

    Future<void> handleMessage(RemoteMessage message) async {

    print('Foreground Message Received: payload ${message.data}');



    // Extract title and body from the data payload

    String title = message.data['title_en'] ?? 'Default Title';

    String body = message.data['body_en'] ?? 'Default Body';



    await _showLocalNotification(title, body);

    }



    // Show local notification function

    Future<void> _showLocalNotification(String title, String body) async {

    await _localNotification.show(

    DateTime.now().millisecondsSinceEpoch ~/ 1000, // Unique ID

    title,

    body,

    NotificationDetails(

    android: AndroidNotificationDetails(

    _androidNotificationChannel.id,

    _androidNotificationChannel.name,

    channelDescription: _androidNotificationChannel.description,

    importance: Importance.high,

    priority: Priority.high,

    icon: '@mipmap/aa', // Ensure this icon exists in your resources

    ),

    ),

    );

    }



    // Initialize local notification settings

    Future<void> initLocalNotification() async {

    const AndroidInitializationSettings androidInitSettings = AndroidInitializationSettings('@mipmap/ic_launcher');

    const InitializationSettings initSettings = InitializationSettings(android: androidInitSettings);



    await _localNotification.initialize(initSettings);

    await _localNotification

    .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()

    ?.createNotificationChannel(_androidNotificationChannel);

    }



    // Initialize push notifications with Firebase

    Future<void> initPushNotification() async {

    // Set foreground notification presentation options for iOS (if applicable)

    await _firebaseMessaging.setForegroundNotificationPresentationOptions(

    alert: true,

    badge: true,

    sound: true,

    );



    // Set up background message handler

    FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);



    // Listen to messages when the app is in the foreground

    FirebaseMessaging.onMessage.listen(handleMessage);



    // Listen to messages that open the app when tapped

    FirebaseMessaging.onMessageOpenedApp.listen(handleMessage);

    }



    // Complete notification initialization

    Future<void> initNotification() async {

    // Request notification permissions

    await _firebaseMessaging.requestPermission();



    // Get the device token (optional)

    String? token = await _firebaseMessaging.getToken();

    print("Device Token: $token");



    // Initialize local and push notifications

    await initLocalNotification();

    await initPushNotification();

    }



    // Retrieve device token (for sending notifications via server)

    Future<String?> getDeviceToken() async {

    String? token = await _firebaseMessaging.getToken();

    return token;

    }

    }


    Does anyone have an idea on how to fix this problem?

    Continue reading...

Compartilhe esta Página