0

if the user press on FCM notification, I want to open the app and display dialog containing the FCM content.

now it appears only if the app is open, but if the app is closed I get the notification, when I press it, the app opens but I don't have the dialog.

the app screen sequence main.dart --> loading_screen.dart --> home_screen.dart

What I came to :

main.dart code

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,
    );
  }
}

no edit in loading_screen.dart

home_screen.dart code

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()),
          )
   }
}

Can someone tell me what I am missing?

H Amr
  • 177
  • 1
  • 13
  • please check [this](https://stackoverflow.com/questions/74005059/do-an-action-after-click-on-notification-flutter), may help you – Tarek Apr 03 '23 at 10:32

1 Answers1

0

The below code will work for you.

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

Updated Code


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());
    }
Rohan Jariwala
  • 1,564
  • 2
  • 7
  • 24