0
0
FlutterHow-ToBeginner · 4 min read

How to Use Cloud Messaging in Flutter: Setup and Example

To use Firebase Cloud Messaging (FCM) in Flutter, add the firebase_messaging package, configure Firebase in your app, and handle message events using the package's API. This enables your app to receive and display push notifications from the cloud.
📐

Syntax

The main steps to use Firebase Cloud Messaging in Flutter are:

  • Add firebase_messaging to pubspec.yaml.
  • Initialize Firebase in your app.
  • Create an instance of FirebaseMessaging.
  • Request notification permissions (especially on iOS).
  • Listen for messages using onMessage, onMessageOpenedApp, and background handlers.
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 for iOS
  NotificationSettings settings = await messaging.requestPermission();

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

  runApp(MyApp());
}
💻

Example

This example shows a minimal Flutter app that initializes Firebase, requests notification permission, and listens for incoming messages to print them in the console.

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

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Background message received: ${message.messageId}');
}

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

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  runApp(MyApp());
}

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

class _MyAppState extends State<MyApp> {
  String _message = 'No message received yet';

  @override
  void initState() {
    super.initState();
    FirebaseMessaging.instance.requestPermission();

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      setState(() {
        _message = 'Message: ${message.notification?.title ?? 'No Title'}';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('FCM Flutter Example')),
        body: Center(child: Text(_message)),
      ),
    );
  }
}
Output
App shows a screen with text 'No message received yet' initially, then updates to 'Message: <title>' when a push notification arrives while app is foreground.
⚠️

Common Pitfalls

  • Not initializing Firebase: Forgetting Firebase.initializeApp() causes errors.
  • Missing permissions: On iOS, you must request notification permissions explicitly.
  • Not handling background messages: Background messages require a separate handler function.
  • Incorrect Firebase setup: Ensure google-services.json (Android) and GoogleService-Info.plist (iOS) are properly added.
  • Not testing on real devices: Push notifications often don't work on emulators without Google Play services.
dart
/* Wrong: No Firebase initialization */
void main() {
  runApp(MyApp());
}

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

Quick Reference

Key steps to remember when using Firebase Cloud Messaging in Flutter:

  • Add firebase_core and firebase_messaging packages.
  • Initialize Firebase in main() before running the app.
  • Request notification permissions on iOS.
  • Use FirebaseMessaging.onMessage for foreground messages.
  • Use FirebaseMessaging.onBackgroundMessage for background messages.
  • Test on real devices for reliable results.

Key Takeaways

Always initialize Firebase with Firebase.initializeApp() before using messaging.
Request notification permissions explicitly on iOS devices.
Use onMessage and onBackgroundMessage listeners to handle incoming messages.
Add the required Firebase config files to your Android and iOS projects.
Test push notifications on real devices, not just emulators.