onMessage
- Flutter course
- Advanced
- Lesson 28/69
- 4 min
Catch foreground notifications with onMessage.
The onMessage stream
The onMessage stream catches notifications that arrive while the app is in the foreground. This stream returns a Stream<RemoteMessage> and is listened to with listen. It is used to show a snackbar or dialog when a notification arrives in foreground.
messaging.onMessage.listen((message) {
print(message.title);
});The RemoteMessage class
RemoteMessage is the class that holds the data of an incoming notification. You access the notification content through its title, body, and data fields. The data field carries custom key-value pairs.
messaging.onMessage.listen((message) {
print(message.data['key']);
});Practice Listen to the onMessage stream
Get the messaging instance, listen to the onMessage stream with listen and print message.title. Wait 10 milliseconds after starting to listen.
Starter code
class RemoteMessage {
final String title;
RemoteMessage(this.title);
}
class FirebaseMessaging {
static final FirebaseMessaging instance = FirebaseMessaging._();
FirebaseMessaging._();
Stream<RemoteMessage> get onMessage => Stream.value(RemoteMessage('Merhaba'));
}
void main() async {
// onMessage akışını dinle
// title yazdır
}Sample solution
class RemoteMessage {
final String title;
RemoteMessage(this.title);
}
class FirebaseMessaging {
static final FirebaseMessaging instance = FirebaseMessaging._();
FirebaseMessaging._();
Stream<RemoteMessage> get onMessage => Stream.value(RemoteMessage('Merhaba'));
}
void main() async {
FirebaseMessaging.instance.onMessage.listen((message) {
print(message.title);
});
await Future.delayed(Duration(milliseconds: 10));
}Expected output
Merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does the onMessage stream emit an event?
- When the device boots
- When a notification arrives while the app is in foreground Correct answer
- Only during initialization
- Only when the app is closed
Explanation: onMessage emits only when a notification arrives while the app is in foreground; it does not fire in background or when closed.
2 Listen to onMessage
FirebaseMessaging.instance.____.listen((message) {
print(message.title);
});
FirebaseMessaging.instance.onMessage.listen((message) {
print(message.title);
});
Explanation: onMessage is a getter that returns a Stream; it needs no parentheses and is listened to directly with .listen.
3 onMessage parts
| Term | Meaning |
|---|---|
onMessage |
Foreground stream |
RemoteMessage |
Notification data |
listen |
Listens to the stream |
foreground |
App in foreground |