TheFishTheySay
TheFishTheySay

Reputation: 289

How to send data from background service to main application in flutter

I am running a background servie and at a specific time, I want to send some data in form of JSON string to my application. It may happen that my app is currently terminated, so I am using app laucher plugin to open my application. After opening the application, I want to send some data to application so as to display it. So, how can I send the message and recieve it in my main application (I will have to change the state of my widget once I recieve the data)?

Upvotes: 2

Views: 3223

Answers (3)

You can simply set a port for each isolate (the main and the background) and listen to the events, Eg:. you can send your data:

IsolateNameServer.lookupPortByName('mainIsolate')?.send('Hi from background');

and listen to the event:

void initListinPort() {
  ReceivePort port = ReceivePort();
  IsolateNameServer.registerPortWithName(port.sendPort, 'mainIsolate');
  // Listen for messages from the background isolate
  port.listen((msg) {
    print('message from background service: $msg');
  });
}

and i think it's much better than store and restore your message, since you dont have to use await or any overhead logic and you'll be able to send all types of data Null bool int double String List Map Set TransferableTypedData SendPort Capability Type

however, sometimes you may have to stringify your object

Upvotes: 0

Developer
Developer

Reputation: 640

Definitely agree with above answer , But if you want to secure your application more then you can use Flutter_Secure_Storage. It is alternative to Shared_Preference :)

Upvotes: 1

TheUltimateOptimist
TheUltimateOptimist

Reputation: 1229

I am not completely sure if this works, but I think instead of somehow sending the data from the background service to the main application you could probably save it in shared preferences or local database or using hive or something similar and simply retrieve it in your main application.

Upvotes: 2

Related Questions