Search code examples
flutterdartpush-notificationfirebase-cloud-messaging

Flutter Push Notification Not Showing


I want to make push notif with firebase in flutter, i get the token and send test on device, but the notification is not show. Messaging Firebase Console

This is my code.

<main.dart>

import 'package:firebase_core/firebase_core.dart';

import 'api/firebase_api.dart';
import 'firebase_options.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await FirebaseApi().initNotifications();
  runApp(TesMagenta());
}

<firebase_api.dart>

import 'package:firebase_messaging/firebase_messaging.dart';

class FirebaseApi{
  //Instance for firebase messaging
  final _firebaseMessaging = FirebaseMessaging.instance;

  //Function initialize Notification
  Future<void> initNotifications() async {
    //Request permittion from user
    await _firebaseMessaging.requestPermission();

    //Fetch fcm token for device
    final fCMToken = await _firebaseMessaging.getToken();

    //Print token
    print('Token: $fCMToken');

  }

//Handle received messages

//Function initialize foreground n background settings

}

my console

D/FLTFireMsgReceiver( 5352): broadcast received for message
W/FirebaseMessaging( 5352): Unable to log event: analytics library is missing
W/FirebaseMessaging( 5352): Unable to log event: analytics library is missing

Solution

  • Here is complete code to setup firebase push notification

    use this code in main.dart

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
      RemoteMessage? initialMessage =
      await FirebaseMessaging.instance.getInitialMessage();
      // If the message also contains a data property with a "type" of "chat",
      // navigate to a chat screen
      if (initialMessage != null) {
        _handleMessage(initialMessage);
      }
      FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
    
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return OverlaySupport(
          global: true,
          child: MaterialApp(
            navigatorKey: navigatorKey,
            title: 'Flutter Demo',
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              primarySwatch: primaryColor,
            ),
            home: const YourFirstPage(),
          ),
        );
      }
    }
    
    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      // If you're going to use other Firebase services in the background, such as Firestore,
      // make sure you call `initializeApp` before using other Firebase services.
      await Firebase.initializeApp();
    
      print("Handling a background message: ${message.messageId}");
      print("Handling a background message: ${message.data.toString()}");
    }
    
    void _handleMessage(RemoteMessage message) {
      print("notification clicked");
      
    }
    
    // check notificaiton permission
    void checkNotificationPermission() async {
      FirebaseMessaging messaging = FirebaseMessaging.instance;
      NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        announcement: true,
        badge: true,
        carPlay: false,
        criticalAlert: true,
        provisional: true,
        sound: true,
      );
    
      print('User granted permission: ${settings.authorizationStatus}');
    }
    

    and make sure you have followed all steps to setup firebase and firebase messaging.