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

2

5

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

Autoclave answered 1/2, 2023 at 8:35 Comment(0)
L
13

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?

Leacock answered 1/2, 2023 at 10:17 Comment(3)
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 possibleIncognizant
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. } #48404286Leacock
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 !Leacock
D
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.

Downswing answered 3/8, 2023 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.