0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Firebase Cloud Messaging (FCM) with Flutter

To use FCM with Flutter, add the firebase_messaging package to your project, initialize Firebase in your app, and set up message handlers to receive notifications. This lets your Flutter app receive push notifications from Firebase Cloud Messaging.
📐

Syntax

Here is the basic syntax to set up Firebase Cloud Messaging in Flutter:

  • FirebaseMessaging.instance: Access the FCM instance.
  • requestPermission(): Ask user permission for notifications.
  • getToken(): Get the device token to send messages.
  • onMessage, onMessageOpenedApp: Listen for incoming messages.
dart
import 'package:flutter/widgets.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FirebaseMessaging messaging = FirebaseMessaging.instance;

  // Request permission
  NotificationSettings settings = await messaging.requestPermission();

  // Get device token
  String? token = await messaging.getToken();

  // Listen for messages
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print('Message received: ${message.messageId}');
  });

  runApp(MyApp());
}
💻

Example

This example shows a Flutter app that initializes Firebase, requests notification permission, gets the FCM token, and listens for messages while the app is in the foreground.

dart
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _token = 'Fetching token...';
  String _message = 'No messages yet';

  @override
  void initState() {
    super.initState();
    setupFCM();
  }

  void setupFCM() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;

    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      String? token = await messaging.getToken();
      setState(() {
        _token = token ?? 'No token';
      });

      FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        setState(() {
          _message = message.notification?.title ?? 'Message received';
        });
      });
    } else {
      setState(() {
        _token = 'Permission denied';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('FCM with Flutter')),
        body: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('FCM Token:', style: TextStyle(fontWeight: FontWeight.bold)),
              SelectableText(_token),
              SizedBox(height: 20),
              Text('Latest Message:', style: TextStyle(fontWeight: FontWeight.bold)),
              Text(_message),
            ],
          ),
        ),
      ),
    );
  }
}
Output
App shows the FCM token and updates the latest message title when a notification arrives while the app is open.
⚠️

Common Pitfalls

Common mistakes when using FCM with Flutter include:

  • Not initializing Firebase before using FirebaseMessaging.
  • Forgetting to request notification permissions on iOS.
  • Not handling background or terminated state messages properly.
  • Using outdated firebase_messaging versions causing API mismatches.

Always check platform setup steps in Firebase console and your app manifest files.

dart
/* Wrong: Using FirebaseMessaging before Firebase.initializeApp() */
void main() {
  // Error: Firebase not initialized
  // FirebaseMessaging messaging = FirebaseMessaging.instance;
  runApp(MyApp());
}

/* Right: Initialize Firebase first */
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging messaging = FirebaseMessaging.instance;
  runApp(MyApp());
}
📊

Quick Reference

Key steps to use FCM in Flutter:

  • Add firebase_core and firebase_messaging packages.
  • Initialize Firebase in main().
  • Request notification permissions (especially on iOS).
  • Get device token with getToken().
  • Listen for messages with onMessage and onMessageOpenedApp.
  • Configure platform-specific settings (AndroidManifest.xml, Info.plist).

Key Takeaways

Initialize Firebase before using FirebaseMessaging in Flutter apps.
Request notification permissions on iOS to receive push notifications.
Use FirebaseMessaging.onMessage to handle foreground messages.
Get the device token with getToken() to send targeted notifications.
Check platform setup and manifest files to avoid common errors.