Search code examples
flutterdartfirebase-cloud-messaging

Firebase inApp flutter notificaiton is not working and showing no error


here is the code i done. and it works perfectly fine. i tried debugging and the post method is posting everything properly. but the notification is not receiving. here is the whole code

import 'dart:convert';

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
import 'package:http/http.dart' as http;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  Future<bool> callOnFcmApiSendPushNotifications(
      {required String title, required String body}) async {
    const postUrl = 'https://fcm.googleapis.com/fcm/send';
    final data = {
      "to": "/topics/myTopic",
      "notification": {
        "title": title,
        "body": body,
      },
      "data": {
        "type": '0rder',
        "id": '28',
        "click_action": 'FLUTTER_NOTIFICATION_CLICK',
      }
    };

    final headers = {
      'content-type': 'application/json',
      'Authorization':
          'key=AAAAMKtOtwQ:APA91bFCCEwWKU75EVeyc912ghzS0Yon8dlfjiFEiw9nfdtfrq0BCBWS3x_ioTqX1l2MUDO_Wb-c2PbRl66Z_2mvFEsPRbDEAPTSCEb7SVFykecC_BWGR5P2La8T47eIfCiMvU9oJDJd'
    };

    final response = await http.post(Uri.parse(postUrl),
        body: json.encode(data),
        encoding: Encoding.getByName('utf-8'),
        headers: headers);

    if (response.statusCode == 200) {
      print('test ok push CFM');
      return true;
    } else {
      print(' CFM error');
      return false;
    }
  }

  void _incrementCounter() {
    setState(() {
      callOnFcmApiSendPushNotifications(
          title: 'fcm by api2', body: 'its working fine2');
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

is there anything i need to fix from firebase or any problem with the code. i can't figure it out please help me

i tried debugging and printing everywhere in the code file. and everything work fine. and i enabled everything ive to do from firebase. still not getting a notification

also I'm testing this in android


Solution

  • When getting messages, you will need a way to handle those messages and it will depend if the message is received while the app is in the foreground, background or closed.

    This document shows how to setup the listener for messages received in the foreground:

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');
    
      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });
    

    This document shows how to do this for messages received while in the background:

    @pragma('vm:entry-point')
    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      // If you're going to use other Firebase services in the background, such as Firestore,
      // make sure you call `initializeApp` before using other Firebase services.
      await Firebase.initializeApp();
    
      print("Handling a background message: ${message.messageId}");
    }
    
    void main() {
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
      runApp(MyApp());
    }
    

    You can see how these methods are implemented in this sample.

    Then, to receive the messages you will need to suscribe to the topics. In the sample I mentioned, you can see this in the method:

    Future<void> subscribeToTopic(String topic) async {
        await firebaseMessaging.subscribeToTopic(topic);
      }