Omar Abdelazeem
Omar Abdelazeem

Reputation: 411

Can not get background notifications in android using flutter

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

Upvotes: 0

Views: 1686

Answers (1)

Rida Rezzag
Rida Rezzag

Reputation: 3963

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

Upvotes: 1

Related Questions