X

Flutter firebase push notification

 

Flutter firebase push notification :

Flutter firebase push notification is used to send user the updates regarding the app services, it is used to improve and provide better performance by making user know the latest updates regarding the service he has opted for.

Push notifications are a key elements in every app to make user interact with the app every now and then.Also social networking app’s like whatsapp, facebook, twitter, youtube, gmail and much more… use them in alerting the user with new arrivals.

 

Google firebase provides a user interface to send push notifications to devices both android & iOS aswell.We can also send a images in flutter firebase push notification.

Food delivery apps swiggy, zomato, uber eats, food panda &  cloud image storage apps like google photos, Picasso use these image based push notifications.

We are going to deal with displaying firebase push notification in android and iOS devices can observe the screen’s

Flutter firebase push notification video tutorial :

Go through the below tutorial for more detailed information.

 

Firebase push notification Project Structure :

This image depicts the project structure of firebase push notification implementation.

 

pubspec.yaml :

We need to add flutter_local_notifications, firebase_messaging plugins to our dependency’s and also provide the versions accordingly to latest available.

dependencies:
  flutter:
    sdk: flutter
  flutter_local_notifications: 
  firebase_messaging:

 

 

Google Firebase Console :

Need to make some configurations in google firebase console to get google-services.json for android and GoogleService-Info.plist for iOS.

 

 

Add Android and iOS project to your project

            

Then we get the two configuration files which we need to add in our project folder as below

                         

 

Then add initialization codes for android & iOS

 

Android :

 

iOS :

main.dart :

Add a default class MyApp to the main() and extend it with StatelessWidget

import 'package:flutter/material.dart';
import 'notifications.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Notifications(title: 'Push Notifications'),
    );
  }
}

 


Now navigate the home to Notifications.dart

 

notifications.dart :

Initialize firebase messaging and flutter local notification plugins

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

@override
void initState() {
  super.initState();
  var initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');

  var initializationSettingsIOS = IOSInitializationSettings(
      onDidReceiveLocalNotification: onDidReceiveLocalNotification);

  var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS);

  flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: onSelectNotification);

  _firebaseMessaging.configure(
    onMessage: (Map<String, dynamic> message) async {
      print('on message $message');
      displayNotification(message);
    },
    onResume: (Map<String, dynamic> message) async {
      print('on resume $message');
    },
    onLaunch: (Map<String, dynamic> message) async {
      print('on launch $message');
    },
  );
  _firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true));
  _firebaseMessaging.onIosSettingsRegistered
      .listen((IosNotificationSettings settings) {
    print("Settings registered: $settings");
  });
  _firebaseMessaging.getToken().then((String token) {
    assert(token != null);
    print(token);
  });
}

 


 

Display Android Notification :

Future<void> displayNotification(Map<String, dynamic> message) async {
  var androidPlatformChannelSpecifics = AndroidNotificationDetails(
    'channel-id',
    'fcm',
    'androidcoding.in',
    importance: Importance.max,
    priority: Priority.high,
  );
  var iOSPlatformChannelSpecifics = IOSNotificationDetails();
  var platformChannelSpecifics = NotificationDetails(
    androidPlatformChannelSpecifics,
    iOSPlatformChannelSpecifics,
  );
  await flutterLocalNotificationsPlugin.show(
    0,
    message['notification']['title'] as String,
    message['notification']['body'] as String,
    platformChannelSpecifics,
    payload: 'fcm',
  );
}

 

 

on Select of notification

Future<void> onSelectNotification(String payload) async {
  if (payload != null) {
    debugPrint('Notification payload: $payload');
  }
  // On Select Android Notifications
}

 

 

Display iOS Notification :

Future<void> onDidReceiveLocalNotification(int id, String title, String body, String payload) async {
  // Display a dialog with the notification details, tap ok to go to another page
  showDialog(
    context: context,
    builder: (BuildContext context) => CupertinoAlertDialog(
      title: Text(title),
      content: Text(body),
      actions: [
        CupertinoDialogAction(
          isDefaultAction: true,
          child: Text('Ok'),
          onPressed: () async {
            Navigator.of(context, rootNavigator: true).pop(); // On select iOS notification
          },
        ),
      ],
    ),
  );
}

 

 

Flutter firebase push notification output :

This screen depicts the firebase push notification

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

If you have any query on this tutorial on firebase push notification do let us know in the comment section below.If you like this tutorial do like and share for more interesting tutorials.

 

abhishek:
Related Post

This website uses cookies.