0
0
Fluttermobile~20 mins

Push notifications (FCM) in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Push Notification Demo
This screen shows how to receive and display Firebase Cloud Messaging push notifications in a Flutter app.
Target UI
-------------------------
| Push Notification Demo |
-------------------------
|                       |
| Last message received:|
|                       |
| <No message yet>      |
|                       |
-------------------------
Initialize Firebase in the app
Request notification permissions from the user
Listen for incoming FCM messages when app is in foreground
Display the last received message text on the screen
Handle background and terminated state messages with a simple print log
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: PushNotificationDemo(),
    );
  }
}

class PushNotificationDemo extends StatefulWidget {
  const PushNotificationDemo({super.key});

  @override
  State<PushNotificationDemo> createState() => _PushNotificationDemoState();
}

class _PushNotificationDemoState extends State<PushNotificationDemo> {
  String _message = '<No message yet>';

  @override
  void initState() {
    super.initState();
    // TODO: Add Firebase Messaging initialization and listeners here
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Push Notification Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Text('Last message received:\n\n$_message', textAlign: TextAlign.center),
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
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 {
  // This handler runs when app is in background or terminated
  print('Background message received: ${message.messageId}');
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: PushNotificationDemo(),
    );
  }
}

class PushNotificationDemo extends StatefulWidget {
  const PushNotificationDemo({super.key});

  @override
  State<PushNotificationDemo> createState() => _PushNotificationDemoState();
}

class _PushNotificationDemoState extends State<PushNotificationDemo> {
  String _message = '<No message yet>';
  final FirebaseMessaging _messaging = FirebaseMessaging.instance;

  @override
  void initState() {
    super.initState();
    _requestPermission();
    _listenForegroundMessages();
  }

  void _requestPermission() async {
    NotificationSettings settings = await _messaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    print('User granted permission: ${settings.authorizationStatus}');
  }

  void _listenForegroundMessages() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      String notificationBody = message.notification?.body ?? 'No body';
      setState(() {
        _message = notificationBody;
      });
      print('Foreground message received: $notificationBody');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Push Notification Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Text('Last message received:\n\n$_message', textAlign: TextAlign.center),
        ),
      ),
    );
  }
}

This Flutter app uses Firebase Cloud Messaging (FCM) to receive push notifications.

First, Firebase is initialized in main(). We register a background message handler _firebaseMessagingBackgroundHandler to handle messages when the app is not in the foreground.

In the stateful widget, we request notification permissions from the user using requestPermission(). This is important on iOS and Android 13+.

We listen for messages arriving while the app is open using FirebaseMessaging.onMessage. When a message arrives, we update the screen text with the notification body.

Background and terminated messages are logged to the console by the background handler.

This setup covers the basic flow to receive and display FCM push notifications in a Flutter app.

Final Result
Completed Screen
-------------------------
| Push Notification Demo |
-------------------------
|                       |
| Last message received:|
|                       |
| Hello from FCM!       |
|                       |
-------------------------
When a push notification arrives while the app is open, the message text updates on screen.
If the app is in background or closed, the message is logged in console by the background handler.
Stretch Goal
Add a button to display the device's FCM token on screen.
💡 Hint
Use FirebaseMessaging.instance.getToken() to fetch the token and show it in a dialog or text widget.