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

Issue

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?

Solution

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

Answered By – Günter Zöchbauer

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *