Display Push Notification in Flutter

Create Free Backend With Appwrite

Display Push Notification in Flutter

In this section, you will learn how to display push notification in flutter using firebase_messaging package. This package allows you to display push notification in flutter for android, ios, web, and desktop.

Step 1: Create Flutter Project

Let’s create a flutter project called push_notification by flutter create command. Follow the below steps to create a flutter project.

flutter create push_notification
Info

Note: Open the project in your favorite editor and make sure you are in the root directory of the project in terminal.

Step 2: Create Firebase Project

Go to Firebase Console and create a new project. If you already have a project, then you can use that project.

Step 3: Add Firebase to Flutter App

Click on Flutter icon to add firebase to flutter app. You also need to install firebase cli to add firebase to flutter app. You can install firebase cli using the following command. Also follow the instructions from firebase.

Info

Note: If you don’t have npm installed, then you can install it from here.

npm install -g firebase-tools

Command to add firebase to flutter app.

firebase login
firebase init
dart pub global activate flutterfire_cli
flutterfire configure --project=<projectId>

Step 4: Add Packages

Now it’s time to add firebase_core and firebase_messaging package in your pubspec.yaml file. You can add these packages in your pubspec.yaml file as shown below.

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.16.0  
  firebase_messaging: ^14.6.8

Step 5: Create File

In the lib folder, create a new file called firebase_api.dart and add the following code.

import 'package:firebase_messaging/firebase_messaging.dart';

class FirebaseApi{
  final _firebaseMessaging = FirebaseMessaging.instance;

  Future<void> initNotification() async {
    await _firebaseMessaging.requestPermission(
      alert: true,
      badge: true,
      criticalAlert: true,
      sound: true,
    );

    final token = await _firebaseMessaging.getToken();
    print('Token: $token');
  }

  void subscribeToTopic(String topic) async {
    await _firebaseMessaging.subscribeToTopic(topic);
  }
}

Change Main File

In the main.dart file, add the following code.

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  await FirebaseApi().initNotification();
  FirebaseApi().subscribeToTopic('all');
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('Handling a background message ${message.messageId}');
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: NotificationHandler(),
    );
  }
}

class NotificationHandler extends StatefulWidget {
  @override
  _NotificationHandlerState createState() => _NotificationHandlerState();
}

class _NotificationHandlerState extends State<NotificationHandler> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

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

    _firebaseMessaging.getToken().then((String? token) {
      assert(token != null);
      print("Push Messaging token: $token");
    });

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');
      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            content: ListTile(
              title: Text(message.notification!.title!),
              subtitle: Text(message.notification!.body!),
            ),
            actions: <Widget>[
              MaterialButton(
                child: Text('Ok'),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Notification Handler'),
      ),
      body: Center(
        child: Text('Waiting for message...'),
      ),
    );
  }
}

Step 6: Run Flutter Project

Run your flutter project using the following command.

flutter run

Step 7: Send Notification

Open your firebase console and go to Cloud Messaging. Click on New Notification and send a notification. You will see the notification on your device.