Home > Back-end >  after handling foreground notification (FCM) flutter throws [core/no-app] No Firebase App '[DEF
after handling foreground notification (FCM) flutter throws [core/no-app] No Firebase App '[DEF

Time:11-08

I integrated the flutter app with firebase. I have no problem with getting push notifications when the app is in background, but I don't get foreground notifications.

I added handling foreground messages, now it throws FirebaseException ([core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()), although I have added initilalizeApp() in main method.

that is my main:

  WidgetsFlutterBinding.ensureInitialized();

  Firebase.initializeApp().then((value) => print("Firebase initialized"));

  runApp(const MyApp());

and that is how I handled foreground notifications in MyApp:

    // It is assumed that all messages contain a data field with the key 'type'
  Future<void> setupInteractedMessage() async {
    // Get any messages which caused the application to open from
    // a terminated state.
    RemoteMessage? initialMessage =
        await FirebaseMessaging.instance.getInitialMessage();

    // If the message also contains a data property with a "type" of "chat",
    // navigate to a chat screen
    if (initialMessage != null) {
      _handleMessage(initialMessage);
    }

    // Also handle any interaction when the app is in the background via a
    // Stream listener
    FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
  }

  void _listenForMessages() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      if (message.notification != null) {
        setState(() {
          String? body = message.notification?.body;
          if (body != null) {
          } else {}
        });
      }
    });
  }

  void _handleMessage(RemoteMessage message) {
    if (message.data['type'] == 'chat') {
      Navigator.pushNamed(
        context,
        '/chat',
        arguments: message,
      );
    }
  }

  @override
  void initState() {
    super.initState();
    _requestPermission();
    setupInteractedMessage();
    _listenForMessages();
    
  }

  void _requestPermission() async {
    NotificationSettings settings =
        await FirebaseMessaging.instance.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    } else if (settings.authorizationStatus ==
        AuthorizationStatus.provisional) {
    } else {}
  }

all I found on internet for that error it says call initilazieApp() in main method, but I have done that already but the error won't go away.

CodePudding user response:

Use await Firebase.initializeApp(); you have to add the await

  • Related