CodeBlanks Logo Icon CodeBlanks

Summary - Push notification

Combine getToken and onMessage to make a notification screen.

Notification screen

A notification screen combines getToken and onMessage. First the device token is obtained and sent to the server, then the onMessage stream is listened to in order to catch foreground notifications. Together these two steps form the foundation of a notification system.

final token = await messaging.getToken();
messaging.onMessage.listen((msg) {
  print(msg.title);
});

Practice Write a notification flow

Get the messaging instance. First await the token with getToken and print it. Then listen to the onMessage stream and print message.title. Wait 10 milliseconds.

Starter code

main.dart
class RemoteMessage {
  final String title;
  RemoteMessage(this.title);
}

class FirebaseMessaging {
  static final FirebaseMessaging instance = FirebaseMessaging._();
  FirebaseMessaging._();
  Future<String?> getToken() async => 'token123';
  Stream<RemoteMessage> get onMessage => Stream.value(RemoteMessage('Merhaba'));
}

void main() async {
  // token al ve yazdır
  // onMessage dinle, title yazdır
}

Sample solution

main.dart
class RemoteMessage {
  final String title;
  RemoteMessage(this.title);
}

class FirebaseMessaging {
  static final FirebaseMessaging instance = FirebaseMessaging._();
  FirebaseMessaging._();
  Future<String?> getToken() async => 'token123';
  Stream<RemoteMessage> get onMessage => Stream.value(RemoteMessage('Merhaba'));
}

void main() async {
  final token = await FirebaseMessaging.instance.getToken();
  print(token);
  FirebaseMessaging.instance.onMessage.listen((message) {
    print(message.title);
  });
  await Future.delayed(Duration(milliseconds: 10));
}

Expected output

token123
Merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How are token and onMessage used together on a notification screen?

  • Token and onMessage are the same variable
  • Only the token is printed, onMessage is ignored
  • Token is obtained and sent to server, onMessage catches foreground notifications Correct answer
  • onMessage generates the token

Explanation: The token identifies the device and is sent to the server; onMessage catches foreground notifications. Together they form the notification system.

2 Print the title

Question
print(message.____);
Answer
print(message.title);

Explanation: The title field of RemoteMessage holds the notification title; data and body are different content.

3 Notification screen parts

Term Meaning
getToken Device token
onMessage Foreground notification
RemoteMessage Notification object
message.title Notification title

All lessons in Advanced