Mahmoud Ayyash
Mahmoud Ayyash

Reputation: 33

Flutter Firebase background notification handler not updating data

I'm developing a flutter taxi app. The app depends on Firebase messaging to listen to events like if a rider sent a ride request, so the driver should have a firebase notification that the driver app listen to it, so when the notification came, I handle a function to get information about the ride request like rider and place, then show something like (A rider sent a ride request for you. accept/reject). This is the code that listen to the notification came from firebase:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      if (message.data['clickable'] == "1") {
        if (notificationController.isInForeground.isTrue) {
          showNotification(
            id: Random().nextInt(999999999),
            title: message.data['title'] ?? '',
            body: message.data['body'] ?? '',
            data: jsonEncode(message.data),
          );
        }
      } else {
        String? payload = jsonEncode(message.data);
        notificationController.updatePayload(payload);
      }
    });

and this the function I handle:

notificationController.payload.listen((payload) {
      processNotify(payload);
    });

but I faced a problem while the app in the background (The app is not on the screen), I cant update payload value. Here is my firebase background handler:

@pragma('vm:entry-point')
  static Future<void> _firebaseMessagingBackgroundHandler(
      RemoteMessage message) async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp(
      name: 'taxigo',
      options: DefaultFirebaseOptions.currentPlatform,
    );
    if (message.data['clickable'] != "1") {
      NotificationController notificationController = Get.find();
      String? payload = jsonEncode(message.data);
      notificationController.updatePayload(payload);
    }
  }

I tried to use shared preferences like this:

@pragma('vm:entry-point')
  static Future<void> _firebaseMessagingBackgroundHandler(
      RemoteMessage message) async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp(
      name: 'taxigo',
      options: DefaultFirebaseOptions.currentPlatform,
    );
    if (message.data['clickable'] != "1") {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('payload', payload!);
    }
  }

and here to print the value:

notificationController.payload.listen((payload) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      print('${prefs.getString('payload')}');
    });

but it returns null. I noticed something, if I restart my app, and print the payload stored in prefs, It print the old value stored in the last restart. Could you help me

The app must change the payload value while it in the background

Upvotes: 0

Views: 185

Answers (1)

Muhammad Ali
Muhammad Ali

Reputation: 93


  1. Background Handler Limitations: When your app is in the background, the _firebaseMessagingBackgroundHandler is triggered, but the UI and state management systems (like GetX or Riverpod) may not be fully initialized. This makes it difficult to update things like the payload directly.

  2. SharedPreferences Behavior: SharedPreferences works asynchronously, and updates made in the background may not immediately be reflected when the app resumes.

Solution

Instead of trying to immediately update the payload, you can store the incoming data in SharedPreferences during the background process and then retrieve and update the UI or state when the app comes back to the foreground.

Here's how you can adjust your code:

Background Handler

@pragma('vm:entry-point')
static Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    name: 'taxigo',
    options: DefaultFirebaseOptions.currentPlatform,
  );

  if (message.data['clickable'] != "1") {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? payload = jsonEncode(message.data);
    await prefs.setString('payload', payload);
  }
}

On App Resume or Foreground

When your app resumes or comes to the foreground, you can check if there’s any stored payload in SharedPreferences and then update your controller or UI accordingly.

@override
void initState() {
  super.initState();
  // Check for payload when the app starts or resumes
  _checkAndUpdatePayload();
}

void _checkAndUpdatePayload() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String? storedPayload = prefs.getString('payload');
  if (storedPayload != null) {
    notificationController.updatePayload(storedPayload);
    // Optionally clear the payload after processing
    await prefs.remove('payload');
  }
}

Listening for Changes

You can keep your existing listener but ensure it checks SharedPreferences when the app is in the foreground:

notificationController.payload.listen((payload) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String? storedPayload = prefs.getString('payload');
  if (storedPayload != null) {
    // Update or process the stored payload
    processNotify(storedPayload);
    // Clear the payload after processing
    await prefs.remove('payload');
  }
});

Summary

  • Use SharedPreferences to store payload data in the background.
  • On app resume, check and process any stored payloads.
  • Make sure to clear the SharedPreferences after processing the payload to avoid processing the same data multiple times.

Upvotes: 0

Related Questions