3

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

EmirBashiri
  • 53
  • 1
  • 4

2 Answers2

8

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?

Clevino Alrin
  • 204
  • 2
  • 9
  • can you please explain how it works with details, and where backgroundHandler call. also in backgroundhandler i want to navigate to specific screen so how it is possible – Adnan haider May 26 '23 at 07:04
  • main() { /* callback is set to the NotificationService (Firebase or whatever) via the registerCallback method( just named it so, check out the code i link below for proper method name in case of Firebase) */ NotificationService.registerCallback(backgroundHandler); } ClassABC { void getLetter() => print('a and b'); } // Notice how this is outside of classABC scope and main scope. backgroundHandler() { // Put handling code here. } https://stackoverflow.com/questions/48403786/how-to-open-particular-screen-on-clicking-on-push-notification-for-flutter – Clevino Alrin May 27 '23 at 06:36
  • 1
    You need to use a global Scaffold key in order to navigate to specific page since no context is available... follow the link for code and more info ! – Clevino Alrin May 27 '23 at 06:43
0

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.

Raul Mabe
  • 453
  • 5
  • 15