0

I am using FCM to push notifications with flutter , foreground notifications works well but when in background it does not get any notification .

here is my code

class Home extends StatefulWidget {

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

class _HomeState extends State<Home> {
  String token = '';
  final FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;

  @override
  void initState() {
    getToken();

    firebaseMessaging.requestPermission(
        alert: true, badge: true, provisional: true, sound: true);

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print("onMessage: $message");
    });


    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print("onMessageOpenedApp: $message");
    });


    super.initState();
  }

  void getToken() async {
    token = (await firebaseMessaging.getToken())!;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text("Token : $token")),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          print(token);
        },
        child: Icon(Icons.print),
      ),
    );
  }
}
2
  • 1
    Code isn't visible in your post. Are notification permissions allowed? Commented Sep 3, 2021 at 23:12
  • now it is shown @HuthaifaMuayyad Commented Sep 3, 2021 at 23:19

1 Answer 1

1

You need to define a top-level named handler, since the last firebase_messaging 10.0.6. Notifications will work in the background first update your firebase_messaging 10.0.6

/// Define a top-level named handler which background/terminated messages will /// call. /// /// To verify things are working, check out the native platform logs.

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

see here the complete example: firebase_messaging/example

if you need a real project example complete example

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately I added it and it doesn't work
You're doing something wrongly i implement it, and it works for me, pay attention it only works on android stock version it won't work on Xiaomi devices for example here is a complete example github.com/FirebaseExtended/flutterfire/tree/master/packages/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.