flutter (dart) 是否能够在单独的隔离中发出 api 请求?

Khá*_* Đỗ 6 dart dart-isolates flutter

我做了一个功能来发布一个主题的通知。它在正常情况下运行良好,然后我将其放入计算功能并希望它可以在后台发布通知。但它不起作用。这是我的代码:

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);
  });
}
Run Code Online (Sandbox Code Playgroud)

调用计算:

compute(onSendMessageInBackGround, 'abc');
Run Code Online (Sandbox Code Playgroud)

注意:正如库所说,我已将 onSendMessageInBackGround 函数放在我的应用程序的顶层

是不是缺少了什么?或者我们不能这样做?

Gün*_*uer 2

您可能需要添加一个returnawait

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

隔离可能会在发出请求之前关闭,因为您没有等待Future