Khánh Vũ Đỗ
Khánh Vũ Đỗ

Reputation: 925

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?

Upvotes: 10

Views: 8223

Answers (3)

Esi're
Esi're

Reputation: 66

Isolates communicate by passing messages back and forth. These messages can be primitive values, such as null, num, bool, double, or String, or simple objects such as the List in this example.

You might experience errors if you try to pass more complex objects, such as a Future or http.Response between isolates.

Got this from the documentation here

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657781

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

Upvotes: 2

mcfly
mcfly

Reputation: 834

Function called from compute must be static or global.

Either i agree with pskink, compute here is not usefull.

Upvotes: 0

Related Questions