Home > database >  Flutter showDialog() when Firebase Cloud Messaging Notification is received
Flutter showDialog() when Firebase Cloud Messaging Notification is received

Time:08-17

I've configured Firebase Cloud Messaging (FCM) as described in the docs and it is working as expected. iOS and Android devices receive a notification, and if the notification is tapped, the application opens.

I would like to show an alert dialog when the notification is tapped and the app opens, since the notification menu on iOS does not show the entire notification body content if it exceeds a certain amount of characters.

I've tried adding to the code provided in the linked docs as follows, but showDialog requires a context. As these methods are defined in the main.dart file, no context is available?

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    if (message.notification != null) {
      showDialog(
          context: context, // suggests importing dart.js
                            // this.context => "invalid reference to 'this' expression" 
          builder: (_) => AlertDialog(
                title: Text(message.notification!.title!),
                content: Text(message.notification!.body!),
              ));
    }
  });
  runApp(const MyApp());
}

CodePudding user response:

You can use GlobalKey:

final navigatorKey = GlobalKey<NavigatorState>();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  FirebaseMessaging messaging = FirebaseMessaging.instance;

  NotificationSettings settings = await messaging.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    if (message.notification != null && navigatorKey.currentContext != null) {
      showDialog(
          context: navigatorKey.currentContext,
          builder: (_) => AlertDialog(
                title: Text(message.notification!.title!),
                content: Text(message.notification!.body!),
              ));
    }
  });
  runApp(
    MaterialApp(
      home: HomePage(),
      // Setting a global key for navigator
      navigatorKey: navigatorKey,
    ),
  );
}
  • Related