Reputation: 6908
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)?
Upvotes: 1
Views: 903
Reputation: 7696
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.
Upvotes: 1