The backgroundHandler needs to be either a static function or a top level function to be accessible as a Flutter entry point

5.8k Views Asked by At

hey guys when I use onDidReceiveBackgroundNotificationResponse in flutter_local_notification I got an error can someone help me?

here is error

here is my code

actually I want navigate to second page after user select my notification in background mode but I got this problem

2

There are 2 best solutions below

3
Clevino Alrin On BEST ANSWER

Put the definition of function used as backgroundHandler outside of any class.

For example:

// If in main.dart
main() {
  // ...
}

ClassABC {
  void getLetter() => print('a and b');
}

// Notice how this is outside of classABC scope and main scope.
backgroundHandler() {
  // Put handling code here.
}

For more clarity, could you post the whole page code?

0
Raul Mabe On

actually I want navigate to second page after user select my notification in background mode but I got this problem

Answering on how to navigate from a Top Level Function:

I made a Singleton which is accesible from Top Level Function. This singleton manages a Stream and emits a new event everytime the user taps on a notification.

import 'dart:async';

import 'package:listsapp/common/types/types.dart';

class ActionNotificationService {
  factory ActionNotificationService() => _instance ??= ActionNotificationService._();

  ActionNotificationService._() : _notificationsController = StreamController.broadcast();

  static ActionNotificationService? _instance;
  final StreamController<JSON> _notificationsController;

  void add(JSON payload) => _notificationsController.add(payload);

  Stream<JSON> getNotificationOpenedStream() => _notificationsController.stream;

  void close() {
    _notificationsController.close();
  }
}

Inside my app I listen to this stream and navigate to the specific screen.

Also, remember to close the singleton stream when your application doesn't need it no more.