在对话框中显示FCMFlutter

yduiuuwa  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(158)

如果用户按下FCM通知,我想打开应用程序并显示包含FCM内容的对话框。
现在它只在应用程序打开时出现,但如果应用程序关闭,我会收到通知,当我按下它时,应用程序打开,但我没有对话框。
应用程序屏幕顺序main.dart --〉loading_screen.dart --〉home_screen.dart
我来到这里:
主.dart代码

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await MobileAds.instance.initialize();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(DPCG());
}

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Handling a background message: ${message.messageId}");
}

class DPCG extends StatefulWidget {
  static void setLocale(BuildContext context, Locale locale) {
    _DPCGState state =
        context.findRootAncestorStateOfType<_DPCGState>();
    state.setLocale(locale);
  }

  @override
  _DPCGState createState() => _DPCGState();
}

class _DPCGState extends State<DPCG> {

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    return MaterialApp(
      home: LoadingScreen(),
      theme: ThemeData.light().copyWith(
        //scaffoldBackgroundColor: Color(0xffd4d4ce),
        appBarTheme: AppBarTheme(
          color: Color(0xffd88820),
        ),
        //primaryColor: Colors.black
      ),
      onGenerateRoute: CustomRouter.allRoutes,
      initialRoute: homeRoute,
    );
  }
}

loading_screen.dart中没有编辑
home_screen.dart代码

class MainHome extends StatefulWidget {
  @override
  _MainHomeState createState() => _MainHomeState();
}

class _MainHomeState extends State<MainHome> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  @override
  void initState() {
    super.initState();
    
    _firebaseMessaging.requestPermission();
    _firebaseMessaging.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification notification = message.notification;
      if (notification != null && mounted) {
        print(notification);
        showDialog(
          context: context,
          builder: (BuildContext context) => CupertinoAlertDialog(
            title: Text(notification.title ?? "Notification"),
            content: Text(notification.body ?? "Empty body"),
            actions: <Widget>[
              TextButton(
                child: Text("OK"),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(),
          body: SafeArea(child: Container()),
          )
   }
}

有人能告诉我我错过了什么吗

vfh0ocws

vfh0ocws1#

下面的代码将为您工作。

FirebaseMessaging.instance
          .getInitialMessage()
          .then((RemoteMessage message) {
      print("FirebaseMessaging.getInitialMessage $message");
   });

更新代码

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  
  //This will listen if app is opened by notification message
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage 
    message) {
        .....
        //Display your dialog
      });
      
      runApp(MyApp());
    }

相关问题