Home > front end >  Firebase inApp flutter notificaiton is not working and showing no error
Firebase inApp flutter notificaiton is not working and showing no error

Time:11-04

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

CodePudding user response:

Try to include this line 'origin': 'http://localhost', in your header to make it act like if you are using browser...so, your header should be like this:

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

CodePudding user response:

Subscribe to /topics/myTopic topic.

await FirebaseMessaging.instance.subscribeToTopic("/topics/myTopic");

See Topic messaging on Flutter for the details.

Remember that messages received while the application is in the foreground will not display a visible notification.

  • Related