收到 Firebase 云消息通知时 Flutter showDialog()

Joh*_*ton 2 firebase flutter firebase-cloud-messaging

我已按照文档中的描述配置了 Firebase Cloud Messaging (FCM),并且它按预期工作。iOS 和 Android 设备会收到通知,如果点击通知,应用程序就会打开。

我想在点击通知并打开应用程序时显示一个警报对话框,因为如果 iOS 上的通知菜单超过一定数量的字符,则不会显示整个通知正文内容。

我尝试添加到链接文档中提供的代码,如下所示,但showDialog需要一个context. 由于这些方法是在main.dart文件中定义的,因此没有可用的上下文?

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());
}
Run Code Online (Sandbox Code Playgroud)

聂超群*_*聂超群 5

您可以使用全局密钥:

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,
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)