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


  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.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật