On this page13 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Data Payload
  4. 2. Reading It Safely
  5. 3. Notification Types as Constants
  6. 4. A Dialog Without a BuildContext
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways
  13. Full Code (Copy-Paste Reference)

Lecture 007: Notification Data & Showing a Dialog

Category2: Push Notifications
Lecture007 of 014
Estimated video length16 min
TargetFlutter 3.44 · Dart 3.12 · FlutterFire (latest)
LevelIntermediate

A notification should do something. We put a type, title, body and image in the message's data, read them in the handler, and show a dialog: from code that has no BuildContext.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lecture 006: the three listeners and notificationHandler.


Learning Objectives

  • Send custom data with a notification
  • Read it safely from message.data
  • Decide what to do with a notification type
  • Show a dialog using a navigatorKey
  • Wait for the first screen with Future.delayed

1. The Data Payload

In the console's notification composer, step Additional options → Custom data, add keys:

KeyValue
noti_typePROMO_ADDED_NOTIFICATION
noti_title20% off today
noti_bodyUse code DART20 at checkout
image_urlhttps://picsum.photos/600/300

They arrive as message.data: always a Map of strings.

2. Reading It Safely

dart
final data = message.data;
final type = data['noti_type'] as String? ?? '';
final title = data['noti_title'] as String? ?? '';

Any key may be missing, so read with as String? and give a fallback. Avoid message.toMap()['data']['noti_type'].toString(): on a message without data it crashes, and .toString() turns a missing value into the text "null".

3. Notification Types as Constants

dart
class NotificationStatus {
  static const promoAdded = 'PROMO_ADDED_NOTIFICATION';
  static const general = 'GENERAL_NOTIFICATION';
}

Constants stop typos: 'PROMO_ADDED_NOTIFICATON' in an if fails silently; NotificationStatus.promoAded doesn't compile.

4. A Dialog Without a BuildContext

The handler runs outside any widget, so it has no context. The navigatorKey given to MaterialApp (Lecture 006) provides one:

dart
final context = navigatorKey.currentContext;
if (context == null) return;     // app not built yet
showDialog(context: context, builder: (_) => const AlertDialog(title: Text('Hi')));

Code Examples

Example 1: The Complete Handler

dart
// lib/firebase_notification_handling.dart
static Future<void> notificationHandler(GlobalKey<NavigatorState> navigatorKey,
    int delaySeconds, RemoteMessage message) async {
  final data = message.data;
  final type = data['noti_type'] as String? ?? '';
  if (type != NotificationStatus.promoAdded && type != NotificationStatus.general) {
    return;
  }

  final title = data['noti_title'] as String? ?? '';
  final body = data['noti_body'] as String? ?? '';
  final imageUrl = data['image_url'] as String? ?? '';

  // Give the first screen time to build after a launch.
  await Future.delayed(Duration(seconds: delaySeconds));

  final context = navigatorKey.currentContext;
  if (context == null || !context.mounted) return;

  showDialog(
    context: context,
    barrierDismissible: true,
    builder: (_) => DialogPromoCode(title: title, body: body, type: type, imageUrl: imageUrl),
  );
}
dart
// lib/dialog_promo_code.dart
import 'package:flutter/material.dart';

class DialogPromoCode extends StatelessWidget {
  const DialogPromoCode({
    super.key,
    required this.title,
    required this.body,
    required this.type,
    required this.imageUrl,
  });

  final String title;
  final String body;
  final String type;
  final String imageUrl;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(title),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (imageUrl.isNotEmpty)
            ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Image.network(imageUrl, height: 140, fit: BoxFit.cover),
            ),
          const SizedBox(height: 12),
          Text(body),
        ],
      ),
      actions: [
        TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK')),
      ],
    );
  }
}

Send the message from section 1 with the app open: after a second, the dialog appears with the image, title and code.

Example 2: Saving It for Later

Apps often keep a notification history. With the Hive course's box from that course, save before showing the dialog:

dart
notificationsBox.add({
  'type': type,
  'title': title,
  'body': body,
  'image_url': imageUrl,
  'date_time': DateTime.now().toIso8601String(),
});

Common Beginner Mistakes

1. navigatorKey.currentState!.context at launch: the app may not be built yet, so ! crashes. Use currentContext and check for null.

2. Reading data with ! and .toString(): crashes on missing data, or shows "null" to the user. Read with as String? ?? ''.

3. Putting numbers or booleans in data: FCM data values are always strings. Send "5", then int.tryParse it.


Best Practices

  • Decide behaviour by a type key; keep types as constants shared with your backend.
  • Validate data before showing anything.
  • Keep the dialog in its own widget file.

Practice Questions

  1. What type are the values in message.data?
  2. Why use a navigatorKey here?
  3. Why wait with Future.delayed before showing the dialog?
  4. Rewrite message.toMap()['data']['id'].toString() safely.

Practice Answers

  1. String.
  2. The handler has no BuildContext; the key gives access to the navigator's context.
  3. After a launch, the first screen needs time to build before a dialog can show.
  4. message.data['id'] as String? ?? ''.

Key Takeaways

  • Custom data arrives in message.data as string key-value pairs.
  • Read every key defensively with a fallback.
  • Use constants for notification types.
  • A navigatorKey lets non-widget code show dialogs: check currentContext first.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file.

lib/notification_status.dart

dart
// Constants for every custom notification type the backend can send - a typo here
// fails to compile instead of silently matching nothing.
class NotificationStatus {
  static const promoAdded = 'PROMO_ADDED_NOTIFICATION';
  static const general = 'GENERAL_NOTIFICATION';
}

lib/dialog_promo_code.dart

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

class DialogPromoCode extends StatelessWidget {
  const DialogPromoCode({
    super.key,
    required this.title,
    required this.body,
    required this.type,
    required this.imageUrl,
  });

  final String title;
  final String body;
  final String type;
  final String imageUrl;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(title),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (imageUrl.isNotEmpty)
            ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Image.network(imageUrl, height: 140, fit: BoxFit.cover),
            ),
          const SizedBox(height: 12),
          Text(body),
        ],
      ),
      actions: [
        TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK')),
      ],
    );
  }
}

lib/firebase_notification_handling.dart

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

import 'dialog_promo_code.dart';
import 'notification_status.dart';

class FirebaseNotificationHandling {
  static Future<void> registerNotificationPermission() async {
    final settings = await FirebaseMessaging.instance.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    print('Notification permission: ${settings.authorizationStatus}');

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  static void firebaseOnMessageNotificationHandle(
      GlobalKey<NavigatorState> navigatorKey) {
    FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
      if (message != null) {
        notificationHandler(navigatorKey, 2, message);
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      notificationHandler(navigatorKey, 2, message);
    });

    FirebaseMessaging.onMessage.listen((message) {
      notificationHandler(navigatorKey, 1, message);
    });
  }

  static Future<void> notificationHandler(GlobalKey<NavigatorState> navigatorKey,
      int delaySeconds, RemoteMessage message) async {
    final data = message.data;
    // Every value in message.data is a String - read defensively, never with '!'.
    final type = data['noti_type'] as String? ?? '';
    if (type != NotificationStatus.promoAdded && type != NotificationStatus.general) {
      return;
    }

    final title = data['noti_title'] as String? ?? '';
    final body = data['noti_body'] as String? ?? '';
    final imageUrl = data['image_url'] as String? ?? '';

    // Give the first screen time to build after a cold-start launch.
    await Future.delayed(Duration(seconds: delaySeconds));

    final context = navigatorKey.currentContext;
    if (context == null || !context.mounted) return; // app not built yet, or gone

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (_) => DialogPromoCode(title: title, body: body, type: type, imageUrl: imageUrl),
    );
  }
}

lib/main.dart

Unchanged from Lecture 006: same MyApp with navigatorKey, same HomeScreen. The handler above now shows a real dialog instead of printing.