1

As document said when handle the background message.

Since the background handler runs in its own isolate outside your applications context, it is not possible to update application state or execute any UI impacting logic. You can however perform logic such as HTTP requests, IO operations (updating local storage), communicate with other plugins etc.

The part of background handler code from document.

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();

  print("Handling a background message: ${message.messageId}");
}

void main() {
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

What' the way to execute the IO operations (updating local storage)?

1 Answer 1

1

There are different ways to store data locally.

One example is using the shared_preferences plugin.

You can write to shared_preferences when you receive the notification like this:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('messageId', message.messageId);
}

Future<void> main() async {
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

The code above writes the messageId to shared_preferences when a message is received from the background.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you help me with this: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences) my code is same as your code but it can't get all third party dependencies.
Try running restarting your app, then runflutter clean && flutter pub get and then run the app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.