Firebase x Flutter: Cloud Messaging
How to push notification in Flutter using Firebase Cloud Messaging (FCM)?

Search for a command to run...
How to push notification in Flutter using Firebase Cloud Messaging (FCM)?

No comments yet. Be the first to comment.
Lessons from Code, Content, and Consistency

Reliability basics: Outbox pattern + why it matters

Introducing Kafka/Redpanda + move to event-driven workflow

Connect Orders ↔ Inventory (first working service-to-service flow)

Inventory service + gRPC + proto contracts



Make sure you do not forget to add the SHA keys to your project. And place the updated google-services.json in the
android/src/folder.
pubspec.yaml file. Make sure you're using the most recent version of the dependencies.dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
firebase_core: ^1.12.0
firebase_messaging: ^11.2.6
get_it: ^7.2.0

main function.Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
lib\services folder, create a file named push_notification.dart to use the Cloud Messaging service.class PushNotificationService {
final FirebaseMessaging _fcm = FirebaseMessaging.instance;
}
Next, add two variables of type ValueNotifier to hold the message text received in the notification. Why ValueNotifier? It's because We want to listen to the notification and change the message based on what we receive from the notification.
class PushNotificationService {
// ...
final ValueNotifier<String?> _title = ValueNotifier(null);
final ValueNotifier<String?> _body = ValueNotifier(null);
ValueNotifier<String?> get getTitle => _title;
ValueNotifier<String?> get getBody => _body;
set setTitle(titleText) {
_title.value = titleText;
}
set setBody(bodyText) {
_body.value = bodyText;
}
}
requestPermission() out of the box.initialise() that will handle all permissions.Future initialise() async {
// Requesting the permission from the user to show the notification
NotificationSettings settings = await _fcm.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
}
Future initialise() async {
// ...
// Continuosaly Listening to notification using [onMessage] stream
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Updating the local values
if (message.notification != null) {
setTitle = message.notification!.title;
setBody = message.notification!.body;
}
});
} else if (settings.authorizationStatus ==
AuthorizationStatus.provisional) {
debugPrint('User granted provisional permission');
} else {
debugPrint('User declined or has not accepted permission');
}
}
onBackgroundMessage() that handles messages that arrive while the app is operating in the background.// Called when the app is in the background or terminated.
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
debugPrint("Handling a background message: ${message.messageId}");
}
class PushNotificationService {
//...
}
main methodFuture<void> main() async {
//...
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
}
When the app is running in the background, we want our users to be able to click on the notification. To accomplish this, we must listen to the FirebaseMessaging class's onMessageOpenedApp stream. Let's use our PushNotification class to build this method.
Future<void> setupInteractedMessage(context) async {
// Handle any interaction when the app is in the background via a
// Stream listener
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
_handleMessage(message, context);
});
}
//..
void _handleMessage(RemoteMessage message, BuildContext context) {
// Updating local values with the values received from the Notification
if (message.notification != null) {
setTitle = message.notification!.title;
setBody = message.notification!.body;
}
//..
// Navigating to specific screen
if (message.data['type'] == 'offer') {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => OfferPage(offerData: message.data),
),
);
}
}
locator.dart class inside lib\services and add the below code.import 'package:fcm_flutter/services/push_notification.dart';
import 'package:get_it/get_it.dart';
//..
GetIt locator = GetIt.instance;
//..
void setupLocator() {
locator.registerLazySingleton(() => PushNotificationService());
}
setupLocator method inside the main method.Future<void> main() async {
//...
setupLocator();
//...
}
title and body. Now let's put these variables to work in the UI.
initialise() method to listen to the notification. In order to interact with the notification while the app is running in the background, we must also call the PushNotification class setupInteractedMessage() from within the initState() method.final PushNotificationService pushNotificationService =
locator<PushNotificationService>();
//..
@override
void initState() {
pushNotificationService.initialise();
pushNotificationService.setupInteractedMessage(context);
super.initState();
}
title and body content with ValueListenableBuilder.ValueListenableBuilder<String?>(
valueListenable: pushNotificationService.getTitle,
builder: (context, title, _) {
return Text("${title ?? ""} ,
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
);
},
)
//....
ValueListenableBuilder<String?>(
valueListenable: pushNotificationService.getBody,
builder: (context, body, _) {
return Text("${body?? ""} ,
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
);
},
)

Remember to include the
intent-filterelement in the AndroidManifest.xml file under the tag.
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>

subscribeToTopic method with the topic name:await FirebaseMessaging.instance.subscribeToTopic('weather');
unsubscribeFromTopic method with the topic name:await FirebaseMessaging.instance.unsubscribeFromTopic('weather');
Make sure your
google-services.jsonfile is included.
