Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is flutter (dart) able to make an api request in separate isolate?

I made a function to post notification to a topic. It works great in normally, then I put it in compute function and hope it can posts notification in the background. But it not works. Here is my code:

void onSendMessageInBackGround(String message) {
  Future.delayed(Duration(milliseconds: 3000)).then((_) async{
    Client client = Client();
    final requestHeader = {'Authorization': 'key=my_server_key', 'Content-Type': 'application/json'};
    var data = json.encode({
      'notification': {
        'body': 'tester',
        'title': '$message',
      },
      'priority': 'high',
      'data': {
        'click_action': 'FLUTTER_NOTIFICATION_CLICK',
        'dataMessage': 'test',
        'time': "${DateTime.now()}",
      },
      'to': '/topics/uat'
    });
    await client.post('https://fcm.googleapis.com/fcm/send', headers: requestHeader, body: data);
  });
}

call compute:

compute(onSendMessageInBackGround, 'abc');

Note: I has put the onSendMessageInBackGround function at the top level of my app as the library said

Is it missing something? or we can't do that?

like image 848
Khánh Vũ Đỗ Avatar asked Nov 16 '18 07:11

Khánh Vũ Đỗ


People also ask

How does Dart isolate work?

Using isolates, your Dart code can perform multiple independent tasks at once, using additional processor cores if they're available. Isolates are like threads or processes, but each isolate has its own memory and a single thread running an event loop.

How do you make Dart isolate?

Create and Start an Isolate. Dart provides the spawn() method to create an isolate. It must be declared with an 'entry point' with a single parameter. This parameter displays a port which isolate use to refer back notification message.


1 Answers

You might need to add a return or await

void onSendMessageInBackGround(String message) {
  return /* await (with async above) */ Future.delayed(Duration(milliseconds: 3000)).then((_) async{

It could be that the isolate shuts down before the request is made because you're not awaiting the Future

like image 104
Günter Zöchbauer Avatar answered Oct 19 '22 06:10

Günter Zöchbauer